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)