链表

参靠浙江大学翁凯老师的链表

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
#include <stdio.h> 
#include <stdlib.h>
typedef struct _node
{
int value;
struct _node *next;
} Link;
typedef struct
{
Link *head;
// Link *tail;
} List;//
void add(List *pList, int num);
void print(List list);

int main(int argc, char const *argv[])
{
int num;
List list;
list.head = NULL;
do{
scanf("%d", &num);
if(num != -1){
add(&list, num);//add
printf("list=%x\n", list);
}
}while(num != -1);
//输出
print(list);
//delete
printf("delete\n");
scanf("%d", &num);
Link *p;
int isFound = 1;
for(p=list.head; p; p=p->next){
if(p->value == num) {
printf("look!\n");
isFound = 0;
Link *q=NULL;
for(p=list.head; p; q=p, p=p->next){
if( p->value == num ) {
if( q ){
q->next = p->next;
} else {
list.head = p->next;
}
free(p);
break;
}
}
printf("delete after:\n");
print(list);
break;
}
}
if( isFound ) {
printf("Not!");
}
//remove:
Link *q=NULL;
for( p=list.head; p; p=q){
q = p->next;
free(p);
}
printf("over!\n");

return 0;
}

void add(List *pList, int num){
//add to linked-list
Link* p=(Link*)malloc(sizeof(Link));
p->value = num;
p->next = NULL;
//find head
Link* last = pList->head;//pHead->Link*
printf("last=%x\n", last);
if(last){
while(last->next){
last = last->next;
printf("last=%x\n", last);
}
//attach
last->next = p;
} else{
pList->head = p;
}
// return head;
}
void print(List list){
//遍历链表
Link* p;
for (p=list.head; p; p=p->next){
printf("%d\t", p->value);
}
printf("\n");
}
作者

manu

发布于

2020-02-14

更新于

2023-01-06

许可协议


:D 一言句子获取中...