237. Delete Node in a Linked List
程序员文章站
2024-02-17 10:40:52
...
Problem
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:
Example
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.
Solution
传统的解决方式需要我们知道链表的头节点,这里采用了一个巧妙的方法,将待删除的节点后的节点A赋值给它,再按常规方法删除节点A
/**
* 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) {
ListNode *p;
p=node->next;
node->val=p->val;
node->next=p->next;
free(p);
}
};
上一篇: isis dis-priority
下一篇: (leetcode)66. 加一
推荐阅读
-
237. Delete Node in a Linked List
-
LeetCode笔记:237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
LeetCode 237. Delete Node in a Linked List
-
237. Delete Node in a Linked List【力扣】
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List
-
237. Delete Node in a Linked List