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.
本题的思路是先虚拟一个新的头节点,连接现有头节点,令p指向头节点,q指向头节点后面的节点,然后连接方式我下图所示,按照①,②,③的顺序连接,①X,②X,③X代表①,②,③连接时断开的。
leetcode代码
包含测试用例的代码class Solution(): def swapPairs(self, head): if head==None or head.next==None: return head else: start=ListNode(0) start.next=head p=start q=start.next while q!=None and q.next!=None: p.next=q.next q.next=p.next.next p.next.next=q p=q q=q.next return start.next
# -*- coding: utf-8 -* class ListNode(object): def __init__(self,val,p=None): self.data = val self.next = p class list(object): def initlist(self,data): self.head = ListNode(data[0]) p = self.head for i in data[1:]: node = ListNode(i) p.next = node p = p.next class Solution(): def swapPairs(self, head): if head==None or head.next==None: return head else: start=ListNode(0) start.next=head p=start q=start.next while q!=None and q.next!=None: p.next=q.next q.next=p.next.next p.next.next=q p=q q=q.next return start.next def shuchu(self,head): p=head while p!=None: print p.data p=p.next s = Solution() l=list() l.initlist([]) p=s.swapPairs(l.head) s.shuchu(p)