237. Delete Node in a Linked List
阿新 • • 發佈:2017-09-01
else 一個 ive code 普通 urn tno next value
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.
思路:
先考慮特殊情況:(1)鏈表為空(2)只有一個節點 -- 都直接返回
普通情況:鏈表不為空,且後續節點也不為空
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ void deleteNode(struct ListNode* node) { if (!node) //鏈表不為空 return; else if (node->next){ //要刪的節點還有後續節點 node->val = node->next->val; node->next = node->next->next; } else //其他情況,如列表不為空且要刪除的是最後一個節點 return; }
237. Delete Node in a Linked List