-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSwap-Nodes-In-Pairs.py
48 lines (43 loc) · 1.13 KB
/
Swap-Nodes-In-Pairs.py
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
48
#! /usr/bin/env python
#! -*- coding=utf-8 -*-
# Date: 2019-11-15
# Author: Bryce
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
################Python Solution 1: (非递归)
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res=[]
dummyHead = ListNode(0)
temp = dummyHead
dummyHead.next = head
while temp.next and temp.next.next:
s1 = temp.next
s2 = s1.next
s = s2.next
temp.next = s2
s2.next = s1
s1.next = s
temp = temp.next.next
res = dummyHead.next
return res
################Python Solution 2: (递归)
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
res = head.next
head.next = self.swapPairs(head.next.next)
res.next = head
return res