【LeetCode & 劍指offer刷題】連結串列題3:18 刪除連結串列中的結點(237. Delete Node in a Linked List)
阿新 • • 發佈:2019-01-05
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
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: 4 -> 5 -> 1 -> 9- 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; */