参考翁恺老师的课程:《C语言程序设计进阶》
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int value;
struct _node *next;
} Node;
typedef struct _list {
Node *head;
// Node *tail;
} List;
void add(List *plist, int number);
void print(List *pList);
int main() {
List list;
list.head = NULL;
// list.tail =NULL;
int number;
do {
scanf("%d", &number);
if (number != -1) {
add(&list, number);
}
} while (number != -1);
//链表打印
print(&list);
//链表查找
scanf("%d", &number);
Node *p;
int isFound = 0;
for (p = list.head; p; p = p->next) {
if (p->value == number) {
printf("找到了\n");
isFound = 1;
break;
}
}
if (!isFound) {
printf("没找到\n");
}
//链表删除
Node *q;
for (q = NULL, p = list.head; p; q = p, p = p->next) {
if (p->value == number) {
if (q) {
q->next = p->next;
} else { list.head = p->next; }
free(p);
break;
}
}
//链表清除
for( p =list.head;p;p=q){
q = p->next;
free(p);
}
return 0;
}
void add(List *plist, int number) {
// add to linked-list
Node *p = (Node *) malloc(sizeof(Node));
p->value = number;
p->next = NULL;
// find the last
Node *last = plist->head;
if (last) {
while (last->next) {
last = last->next;
}// attach
last->next = p;
} else { plist->head = p; }
}
//链表打印
void print(List *pList) {
Node *p;
for (p = pList->head; p; p = p->next) {
printf("%d\t", p->value);
}
printf("\n");
}