原題
給你一個鏈表以及兩個權(quán)值v1和v2勋桶,交換鏈表中權(quán)值為v1和v2的這兩個節(jié)點。保證鏈表中節(jié)點權(quán)值各不相同,如果沒有找到對應(yīng)節(jié)點雨涛,那么什么也不用做。
解題思路
- 基礎(chǔ)的鏈表操作懦胞,寫一個helper函數(shù)替久,根據(jù)head和value找出和value相等的節(jié)點和prev節(jié)點
- 比如給出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