LeetCode 237. Delete Node in a Linked List

来源:互联网 发布:java pop3 编辑:程序博客网 时间:2024/06/05 02:42

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 value3, the linked list should become 1 -> 2 -> 4 after calling your function.


A trick applies to this problem. The linkedList should be changeable. Otherwise, there is no way....

void deleteNode(ListNode* node) {        ListNode* nextNode = node->next;        node->val = nextNode->val;     // copy the value to the former one.        node->next = nextNode->next;   // get ride of next node which has the same value as the former one now.        free(nextNode);   // remember to free it in case it was dynamically allocated. }



0 0