LeetCode:237. 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.

Given linked list -- head = [4,5,1,9], which looks like following:

 

Example 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.

二、解題思路

第一種方法:給的是鏈表頭結點:可以從頭結點開始遍歷到要刪除結點的前一個結點,然後該結點指向要刪除結點的下一個結點,刪除要刪除的結點,複雜度O(n)
第二種方法:給的是要刪除結點:對於非尾結點,將下個結點的內容複製到本結點,在刪除掉下一個結點即可(O(1)),
        但是對尾結點,則只能從鏈表頭結點開始遍歷到尾結點的前一個結點(O(n))

三、代碼實現(第二種方法,因爲題目中給的是要刪除的結點)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        if(node == NULL) return;
        //pnext指向要刪除結點的下一個結點
        ListNode* pnext = node->next;
        //把結點的值賦值給要刪除的這個節點
        node->val = pnext->val;
        //把結點的下一個指向賦值給要刪除的結點
        node->next = pnext->next;
        //經過上面兩步,已經把要刪除結點的下一個結點完全copy到當前的結點了
        //所以,刪除掉下一個結點就行了
        delete pnext;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章