-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path13_DeleteNodeInList.cpp
102 lines (87 loc) · 1.77 KB
/
13_DeleteNodeInList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
};
ListNode *create_list(ListNode **root)
{
ListNode *tmp = NULL, *head = NULL;
int value;
cin >> value;
if (value == -1)
return 0;
head = new(ListNode);
if (head == NULL) return 0;
head->value = value;
tmp = head;
cin >> value;
while (value != -1)
{
tmp->next = new(ListNode);
tmp = tmp->next;
tmp->value = value;
cin >> value;
}
tmp->next = NULL;
*root = head;
return head;
}
void DeleteNode(ListNode **pHead, ListNode* pToBeDeleted) {
if(pHead == NULL || pToBeDeleted == NULL)
return;
if(pToBeDeleted->next != NULL) {
ListNode *pNext = pToBeDeleted->next;
pToBeDeleted->value = pNext->value;
pToBeDeleted->next = pNext->next;
delete pNext;
pNext = NULL;
}
else if(*pHead == pToBeDeleted) {
*pHead = NULL;
delete pToBeDeleted;
pToBeDeleted = NULL;
}
else {
ListNode *pNode = *pHead;
while(pNode != NULL && pNode->next != pToBeDeleted) {
pNode = pNode->next;
}
if(pNode == NULL) {
return;
}
else {
pNode->next = NULL;
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}
}
void PrintList(ListNode *pHead) {
ListNode *pNode = pHead;
while(pNode != NULL) {
cout<<pNode->value<<endl;
pNode = pNode->next;
}
}
void destroy(ListNode *pHead) {
ListNode *tmp = NULL;
while(pHead != NULL)
{
tmp = pHead->next;
delete pHead;
pHead = tmp;
}
}
int main(void)
{
ListNode *root = NULL;
create_list(&root); //input 1, 2, 5, -1
PrintList(root);
DeleteNode(&root, root->next);
PrintList(root);
destroy(root);
return 0;
}