1. 程式人生 > >LintCode Python 簡單級題目 451.兩兩交換鏈表中的節點

LintCode Python 簡單級題目 451.兩兩交換鏈表中的節點

超時 size 上一個 ont nodes fin oot ron 單純

題目描述:

給一個鏈表,兩兩交換其中的節點,然後返回交換後的鏈表。

您在真實的面試中是否遇到過這個題? Yes

樣例

給出 1->2->3->4, 你應該返回的鏈表是 2->1->4->3

挑戰

你的算法只能使用常數的額外空間,並且不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

標簽 鏈表

題目分析:

你的算法只能使用常數的額外空間,即不能新建鏈表;

並且不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

創建三個指針:

  head指向開始交換的節點的上一個節點

  n1指向需要交換的第一個節點,即head.next

  n2指向需要交換的第二個節點,即head.next.next

循環鏈表,通過head不斷交換n1/n2位置即可。

源碼:

# 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
        new = ListNode(0)
        new.next = head
        head = new
        
        while head.next is not None and head.next.next is not None:
            n1 = head.next
            n2 = head.next.next
            # 交換n1、n2
            head.next = n2
            n1.next = n2.next
            n2.next = n1
            # 交換後的鏈表,n1在n2後面,將head指向n1
            head = n1
        
        return new.next
        
    # 不創建鏈表頭是否可行?lintcode報超時。
    def _swapPairs(self, head):
        # Write your code here
        if head is None or head.next is None: 
            return head
            
        new = head
        n1 = head
        n2 = head.next
        while n1.next is not None and n2.next is not None:
            n1.next = n2.next
            n2.next = n1
            n1 = n1.next
        return new

LintCode Python 簡單級題目 451.兩兩交換鏈表中的節點