-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveLinkedListElements.c
152 lines (133 loc) · 2.24 KB
/
RemoveLinkedListElements.c
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <stdlib.h>
#include <stdio.h>
typedef struct node *list;
typedef struct node *position;
typedef struct node *ListNode;
typedef struct node
{
int data;
position next;
}node;
static list init_list(void);
static void delete_list(list L);
static int isempty(list L);
static void insert_node(position L,int data);
static void delete_node(list L,position P);
static position find_last(list L);
static position find_value(list L,int data);
static position find_pre(list L,position P );
static void print(list L);
list init_list(void){
list L = (list)malloc(sizeof(node));
L->next = NULL;
return L;
}
void delete_list(list L){
position P ,next;
P = L;
do{
next = P->next;
free(P);
P = next;
}while(next != NULL);
}
int isempty(list L){
return (L->next == NULL);
}
void insert_node(position P,int data){
position tem ;
tem = (position)malloc(sizeof(node));
tem->data = data;
tem->next = P->next;
P->next = tem;
}
void delete_node(list L,position P){
position pre ;
pre = find_pre( L, P);
if(pre != NULL)
{
pre->next = P->next;
free(P);
}
else
{
printf("delete_node:p is not in the list!\n");
}
}
position find_last(list L){
position P;
P=L;
while(P->next != NULL)
{
P = P->next;
}
return P;
}
position find_value(list L,int data){
position P ;
P = L;
while(P->next != NULL)
{
P = P->next;
if(P->data == data)
return P;
}
return NULL;
}
position find_pre(list L,position P ){
position tem ;
tem = L;
while(tem->next != NULL)
{
if(tem->next == P)
return tem;
tem = tem->next;
}
return NULL;
}
void print(list L){
position P;
if(isempty( L))
{
printf("print: L is a null list!\n");
return ;
}
P = L;
while(P->next !=NULL)
{
P = P->next;
printf("print:%p : %d \n",P,P->data);
}
printf("\n");
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
ListNode removeElements( ListNode head, int val) {
ListNode P;
while((P = find_value( head, val)) != NULL)
{
delete_node(head,P);
}
return head;
}
int main(int argc ,char** argv)
{
int a[1]= {1};
int i=0;
list L;
L = init_list();
print(L);
printf("insert node\n");
for(i=0;i<1;i++)
{
insert_node( L,a[i]);
}
print( L);
L = removeElements(L,1);
print( L);
}