1. 題目描述
- 兩兩交換鏈表中的節點
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
2. 代碼實現
方法1:迭代
將鏈表前兩個節點設爲first、second。初始化一個鏈表current, currnode.next 指向second,先將first.next指向second.next,再將second.next轉向first,最後將currnode設爲first,head從原head第三個節點開始。
執行用時 :28 ms, 在所有 Python 提交中擊敗了24.23%的用戶
內存消耗 :13 MB, 在所有 Python 提交中擊敗了7.69%的用戶
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = ListNode(-1)
currnode = current
if head and head.next:
while head and head.next:
first = head
second = head.next
currnode.next = second
first.next = second.next
second.next = first
currnode = first
head = first.next
return current.next
else:
return head
方法2: 遞歸
從鏈表的頭節點 head 開始遞歸。每次遞歸都負責交換一對節點。由 firstNode 和 secondNode 表示要交換的兩個節點。下一次遞歸則是傳遞的是下一對需要交換的節點。若鏈表中還有節點,則繼續遞歸。交換了兩個節點以後,返回secondNode,因爲它是交換後的新頭。在所有節點交換完成以後,我們返回交換後的頭,實際上是原始鏈表的第二個節點。
執行用時 :28 ms, 在所有 Python 提交中擊敗了24.23%的用戶
內存消耗 :12.7 MB, 在所有 Python 提交中擊敗了7.69%的用戶
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# If the list has no node or has only one node left.
if not head or not head.next:
return head
# Nodes to be swapped
first_node = head
second_node = head.next
# Swapping
first_node.next = self.swapPairs(second_node.next)
second_node.next = first_node
# Now the head is the second node
return second_node