Skip to content

Commit db7bbdc

Browse files
committed
Add C++ solutions for leetcode 237.
1 parent 77be572 commit db7bbdc

2 files changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
/**
7+
* Definition for singly-linked list.
8+
*/
9+
struct ListNode {
10+
int val;
11+
ListNode *next;
12+
ListNode(int x) : val(x), next(NULL) {}
13+
};
14+
15+
class Solution {
16+
public:
17+
void deleteNode(ListNode* node) {
18+
node->val = node->next->val; /* 将要删除的node记作toBeDel, 这一步的作用是将结点toBeDel的value更新为与它的下一个node相等的值 */
19+
node->next = node->next->next; // 将结点toBeDel的下一个结点跳过(删掉)
20+
}
21+
};
22+
23+
// Test
24+
int main()
25+
{
26+
Solution sol; // 5->2->3->8->6
27+
ListNode* head = new ListNode(5);
28+
head->next = new ListNode(2);
29+
head->next->next = new ListNode(3);
30+
head->next->next->next = new ListNode(8);
31+
head->next->next->next->next = new ListNode(6);
32+
head->next->next->next->next->next = nullptr;
33+
34+
auto node = head->next->next; // 要删除的node的val为3
35+
sol.deleteNode(node);
36+
37+
auto p = head;
38+
while (p != nullptr)
39+
{
40+
cout << p->val << " ";
41+
p = p->next;
42+
}
43+
44+
return 0;
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
/**
7+
* Definition for singly-linked list.
8+
*/
9+
struct ListNode {
10+
int val;
11+
ListNode *next;
12+
ListNode(int x) : val(x), next(NULL) {}
13+
};
14+
15+
class Solution {
16+
public:
17+
void deleteNode(ListNode* node) {
18+
*node = *(node->next); // 可以直接使用指针对结构体赋值
19+
}
20+
};
21+
22+
// Test
23+
int main()
24+
{
25+
Solution sol; // 5->2->3->8->6
26+
ListNode* head = new ListNode(5);
27+
head->next = new ListNode(2);
28+
head->next->next = new ListNode(3);
29+
head->next->next->next = new ListNode(8);
30+
head->next->next->next->next = new ListNode(6);
31+
head->next->next->next->next->next = nullptr;
32+
33+
auto node = head->next->next; // 要删除的node的val为3
34+
sol.deleteNode(node);
35+
36+
auto p = head;
37+
while (p != nullptr)
38+
{
39+
cout << p->val << " ";
40+
p = p->next;
41+
}
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)