mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
55 lines
1.6 KiB
Markdown
55 lines
1.6 KiB
Markdown
![]() |
# [237. Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/description/)
|
|||
|
# 思路
|
|||
|
首先要搞清楚题目的意思,题意是给定某个未知链表中的一个节点node,删除这个节点。
|
|||
|
## 思路一
|
|||
|
由于我们不知道这个链表,那么也没法知道node的前一个节点,也就没法按照常规方法删除node。
|
|||
|
但是我们知道node及其之后的节点,而删除之后的链表相当于node之后的每个节点的值都向前移动了一个单位。
|
|||
|
## 思路二(思路一改进)
|
|||
|
为什么要移动所有节点的值呢,我们仅仅需要移动node后面第一个元素值就可以了。即令node -> val = node -> next -> val, 然后删除node->next即可。
|
|||
|
# C++
|
|||
|
## 思路一
|
|||
|
```
|
|||
|
/**
|
|||
|
* 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 *pre;
|
|||
|
while(node -> next){
|
|||
|
node -> val = node -> next -> val;
|
|||
|
pre = node;
|
|||
|
node = node -> next;
|
|||
|
}
|
|||
|
pre -> next = NULL;
|
|||
|
delete node;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|
|||
|
## 思路二
|
|||
|
```
|
|||
|
/**
|
|||
|
* 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 *tmp = node -> next;
|
|||
|
node -> val = tmp -> val;
|
|||
|
node -> next = tmp -> next;
|
|||
|
tmp -> next = NULL;
|
|||
|
delete tmp;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|