[LeetCode] Delete Node in a Linked List 刪除鏈表的節點


 

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

 

這道題讓我們刪除鏈表的一個節點,更通常不同的是,沒有給我們鏈表的起點,只給我們了一個要刪的節點,跟我們以前遇到的情況不太一樣,我們之前要刪除一個節點的方法是要有其前一個節點的位置,然后將其前一個節點的next連向要刪節點的下一個,然后delete掉要刪的節點即可。這道題的處理方法是先把當前節點的值用下一個節點的值覆蓋了,然后我們刪除下一個節點即可,代碼如下:

 

C++ 解法:

class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        ListNode *tmp = node->next;
        node->next = tmp->next;
        delete tmp;
    }
};

 

Java 解法:

public class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM