LintCode 511 [Swap Two Nodes in Linked List]

原题

给你一个链表以及两个权值v1和v2,交换链表中权值为v1和v2的这两个节点。保证链表中节点权值各不相同,如果没有找到对应节点,那么什么也不用做。

解题思路

  • 基础的链表操作,写一个helper函数,根据head和value找出和value相等的节点和prev节点
  • 比如给出3->4->1->5->Null 和 1 返回Node(4)和Node(1)
  • 注意边界情况,如果v1=4, v2=1 那么current1和pre2重合,要特殊考虑

完整代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param {ListNode} head, a ListNode
    # @oaram {int} v1 an integer
    # @param {int} v2 an integer
    # @return {ListNode} a new head of singly-linked list
    def swapNodes(self, head, v1, v2):
        # Write your code here
        dummy = ListNode(0)
        dummy.next = head
        prev1, cur1 = self.findNode(dummy, v1)
        prev2, cur2 = self.findNode(dummy, v2)
        
        if cur1 and cur2:
            prev1.next = cur2
            temp = cur2.next
            if cur1.next == cur2:
                cur2.next = cur1
                cur1.next = temp
            else:
                cur2.next = cur1.next
                prev2.next = cur1
                cur1.next = temp
            
        return dummy.next
        
    def findNode(self, head, value):
        while head.next != None:
            if head.next.val == value:
                return head, head.next
            head = head.next
        return None, None

你可能感兴趣的:(LintCode 511 [Swap Two Nodes in Linked List])