24. Swap Nodes in Pairs
24. Swap Nodes in Pairs
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 head==None or head.next==None: return head temp_head=ListNode(-1) temp_head.next=head prehead=temp_head while prehead.next!=None and prehead.next.next!=None: a=prehead.next b=a.next prehead.next,a.next,b.next=b,b.next,a prehead=a return temp_head.next