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.
先看代碼
class Solution {
public:
void deleteNode(ListNode* node) {
*node = *node->next;
}
};
分析總結
題目的意思是刪除鏈表中一個節點,并且給了一個指向這個節點的指針。
但是大神的代碼只有一行。。。。。。。如何分析?
簡單來看,node
就是要刪除的節點,node->next
就是要刪除的節點的下一個節點,這句代碼的意思把下一個節點復制給要刪除的節點。
讓我們畫個圖形象生動地說明一下~

圖形
怎么樣,是不是很形象生動?
PS:有些童鞋說節點并沒有被刪掉,但是,它確實是從鏈表中刪除了啊~