【LeetCode & 劍指offer刷題】鏈表題3:18 刪除鏈表中的結點(237. Delete Node in a Linked List)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)node

Delete Node in a Linked Listspa

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:
4 -> 5 -> 1 -> 9
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.
Example 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.
Note:
  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

C++
 
/*刪除鏈表中的某一個結點(本題不用考慮尾結點)
通用方法(給的是鏈表頭結點):能夠從頭結點開始遍歷到要刪除結點的上一個結點,而後該結點指向要刪除結點的下一個結點,刪除要刪除的結點,不過需花費O(n)
方法2(給的是要刪除結點):對於非尾結點,將下個結點的內容複製到本結點,在刪除掉下一個結點便可(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 )
    {
      
        // *node = *node->next; //*爲取內容運算符,將指針指向的結構體內容複製過去
       
        //真的刪除
      /*  ListNode* temp = node->next;
        *node = *temp; //將指針指向的結構體內容複製過去 
        delete temp; //刪除多餘的結點*/
       
    if ( node == nullptr ) return ;
    ListNode * pnext = node -> next //保存下一個結點指針,以便以後刪除
    node -> val = pnext -> val ;   //複製值
    node -> next = pnext -> next //複製指針
    delete pnext ; //掌握
       
    }
};
/*
也可用這個(掌握)
    ListNode* pnext = node->next;
    node->val = node->next->val;
    node->next = node->next->next;
    delete pnext;
  */
相關文章
相關標籤/搜索