题目:
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.
代码:oj测试164ms通过
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution:
8 # @param a ListNode
9 # @return a ListNode
10 def swapPairs(self, head):
11
12 if head is None or head.next is None:
13 return head
14
15 dummyhead = ListNode(0)
16 dummyhead.next = head
17 p = dummyhead
18
19 while p.next is not None and p.next.next is not None:
20 tmp = p.next.next.next
21 p.next.next.next = p.next
22 p.next = p.next.next
23 p.next.next.next = tmp
24 p = p.next.next
25
26
27 return dummyhead.next
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution:
8 # @param a ListNode
9 # @return a ListNode
10 def swapPairs(self, head):
11 if head is None or head.next is None:
12 return head
13
14 dummpyhead = ListNode(0)
15 dummpyhead.next = head
16
17 p = dummpyhead
18
19 while p.next is not None and p.next.next is not None:
20 tmp = p.next
21 p.next = p.next.next
22 tmp.next = p.next.next
23 p.next.next = tmp
24 p = p.next.next
25
26 return dummpyhead.next