链表基本操作

建输增删查改反

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
#include <stdio.h>
// null head node
struct node
{
int content;
struct node *next;
};
struct node *createLinklist()
{
struct node *head = malloc(sizeof(struct node));
struct node *p = head;
int input=-1;
while(input!=0)
{
scanf("%d",&input);
struct node *new = malloc(sizeof(struct node));
new->content = input;
new->next = NULL;
p->next = new;
p = p->next;
}
p->next=NULL;
return head;
}

void printLinkList(struct node *head)
{
struct node *p = head->next;
while(p->next!=NULL)
{
printf("%d ",p->content);
p = p->next;
}
printf("\n");
}

void reversePrintLinkList(struct node *head)
{
// 递归出入口
if (head->next!=NULL)
reversePrintLinkList(head->next);
//递归执行体
printf("%d ",head->content);
}

void deleteNode(struct node *head,int label)
{
struct node *p = head;
int i;
for(i=0; i<label-1;i++)
{
p = p->next;
}
p->next = p->next->next;
}

void addNode(struct node *head,int label,int content)
{
struct node *p = head;
int i;
for (i=0; i<label;i++)
{
p = p->next;
}
struct node *new = malloc(sizeof(struct node));
new->content = content;
new->next = p->next;
p->next = new;
}

int findNode(struct node *head,int content)
{
struct node *p = head->next;
int count = 1;
do
{
if (p->content == content)
return count;
else
{
count+=1;
p = p->next;
}
}while(p->next!=NULL);
return -1;
}

int main()
{
struct node *LinkList = createLinklist();
printLinkList(LinkList);

// printf("which one to delete?\n");
// int label;
// scanf("%d",&label);
// deleteNode(LinkList,label);
// printLinkList(LinkList);

// printf("where to add behind and what?\n");
// int label,content;
// scanf("%d %d",&label,&content);
// addNode(LinkList,label,content);
// printLinkList(LinkList);

// printf("what content to find?\n");
// int content;
// scanf("%d",&content);
// printf("found it in position %d",findNode(LinkList,content));

printf("start reversing...\n");
reversePrintLinkList(LinkList->next);
printf("\n");

return 0;
}