Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这一题要求两两交换链表中的元素。题目要求常数时间,即无法使用递归解法。
主要思路是两个两个结点
class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head dummy = ListNode(-1) dummy.next = head prev = dummy cur = head while cur and cur.next: prev.next = cur.next cur.next = prev.next.next prev.next.next = cur prev = cur cur = cur.next return dummy.next