LeetCode/solutions/237. Delete Node in a Linked List.md

55 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```