LintCode Q451 Swap Nodes in Pairs in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年12月8日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def swapPairs(self, head):
# Write your code here
if head is None or head.next is None:
return head
current = head
l1 = ListNode(None)
l2 = ListNode(None)
l1_head = l1
l2_head = l2
count = 0
while current:
if count % 2 == 0:
l1.next = current
l1 = l1.next
else:
l2.next = current
l2 = l2.next
current = current.next
count += 1
l1.next = None
l2.next = None
l1 = l1_head.next
l2 = l2_head.next
current = ListNode(None)
head = current
count = 0
while l2 is not None or l1 is not None:
if count % 2 == 0 and l2:
current.next = l2
l2 = l2.next
current = current.next
elif count % 2 == 1 and l1:
current.next = l1
l1 = l1.next
current = current.next
count += 1
return head.next
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。