带头节点链表(初始化,插入,删除,查找,显示,毁链)
#include<stdio.h>
#include<malloc.h>
#define boolean unsigned char
#define TURE 0
#define FALSE -1
typedef struct LINK {
int data;
struct LINK *next;
}LINK;
LINK* creatOnePNode();
boolean InitializationLINK(LINK *hp);
boolean showLINK(LINK *hp);
boolean destoryLINK(LINK *hp);
LINK* searchLINK(LINK *hp, LINK DATA);
boolean insertLINK(LINK *hp);
boolean deleteLINK(LINK *hp);
boolean deleteLINK(LINK *hp) {
int deleteData;
LINK tmpNode;
LINK *pre;
LINK *tmp;
printf("请输入要删除的数据:");
scanf("%d", &deleteData);
tmpNode.data = deleteData;
pre = searchLINK(hp, tmpNode);
if (hp && hp->next) {
if (pre->next){
tmp = pre->next;
pre->next = tmp->next;
free(tmp);
} else {
printf("没有找到,删除无效!\n");
}
return TURE;
} else {
return FALSE;
}
}
boolean insertLINK(LINK *hp){
int position;
int inputData;
LINK tmpNode;
LINK *pre;
LINK *tmp;
if (hp && hp->next) {
printf("请输入你要插入哪个数据的旁边(左插入):");
scanf("%d", &position);
tmpNode.data = position;
pre = searchLINK(hp,tmpNode);
printf("请输入你要插入的数据:");
scanf("%d", &inputData);
tmp = creatOnePNode();
tmp->data = inputData;
tmp->next = pre->next;
pre->next = tmp;
return TURE;
} else {
return FALSE;
}
}
LINK* searchLINK(LINK *hp, LINK DATA) {
LINK *p;
for (p = hp; p && p->next; p = p->next) {
if (p->next->data == DATA.data) {
// printf("找到了!\n");
return p;
}
}
printf("链表中没有此数据,将会添加到链表末尾处或在删除时操作无效\n");
return p;
}
boolean destoryLINK(LINK *hp) {
LINK *p;
while (hp && hp->next) {
p = hp->next;
hp->next = p->next;
free(p);
}
hp->next = NULL;
}
boolean showLINK(LINK *hp) {
LINK *p;
if (NULL == hp && hp->next ==NULL) {
printf("empty");
} else {
for (p = hp->next; p; p = p->next) {
printf("%d", p->data);
printf(p->next?" ":"\n");
}
}
}
boolean InitializationLINK(LINK *hp) {
int data;
LINK *p;
LINK *tail;
printf("请输入数据:(以-1结束):");
scanf("%d", &data);
if (hp) {
while (-1 != data){
p = creatOnePNode();
p->data = data;
if (NULL == hp->next) {
hp->next = p;
} else {
tail->next = p;
}
tail = p;
printf("请输入数据:(以-1结束):");
scanf("%d", &data);
}
return TURE;
} else {
return FALSE;
}
}
LINK* creatOnePNode() {
LINK *Node;
Node = (LINK*)calloc(1,sizeof(LINK));
return Node;
}
int main() {
LINK head = {0};
InitializationLINK(&head);
showLINK(&head);
insertLINK(&head);
showLINK(&head);
deleteLINK(&head);
showLINK(&head);
destoryLINK(&head);
showLINK(&head);
return 0;
}