-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path24.swap-nodes-in-pairs.py
More file actions
101 lines (86 loc) · 1.84 KB
/
24.swap-nodes-in-pairs.py
File metadata and controls
101 lines (86 loc) · 1.84 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# https://leetcode.com/problems/swap-nodes-in-pairs/description/
#
# algorithms
# Medium (51.86%)
# Likes: 3119
# Dislikes: 198
# Total Accepted: 552K
# Total Submissions: 1.1M
# Testcase Example: '[1,2,3,4]'
#
# Given a linked list, swap every two adjacent nodes and return its head.
#
# You may not modify the values in the list's nodes. Only nodes itself may be
# changed.
#
#
# Example 1:
#
#
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
#
#
# Example 2:
#
#
# Input: head = []
# Output: []
#
#
# Example 3:
#
#
# Input: head = [1]
# Output: [1]
#
#
#
# Constraints:
#
#
# The number of nodes in the list is in the range [0, 100].
# 0 <= Node.val <= 100
#
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# Solution - 1: Recursion
# terminal condition:
# None
# a --> None
# if not head or not head.next:
# return head
# # extract nodes
# prev = head
# curr = head.next
# succ = head.next.next
# # swap the prev and curr
# prev.next = self.swapPairs(succ)
# curr.next = prev
# return curr
# Solution - 2: wihtout recursion, use iteration
dummy_head = ListNode(0)
dummy_head.next = head
prev = dummy_head
while head and head.next:
first = head
second = head.next
prev.next = second
first.next = second.next
second.next = first
prev = first
head = first.next
return dummy_head.next
# @lc code=end