題目說明:給你一個linked list,要你移除指定的節點。要移除的節點不會在該linked list的最後一個並且該節點在linked中是唯一值。要注意的是移除必須就地(in place)
Case 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Case 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
解題思路:由於linked list是不連續的,因此我們在移除時要考慮先將該移除的節點值取代變成下一個節點的值,同時要將要刪除節點的下一個節點指向節點的下下一個節點,有了這個思路程式就很好寫了。
附上程式碼
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val=node.next.val
node.next=node.next.next
要注意的地方就是上面兩行不可以交換,大家可以試試看如果交換結果會變怎樣