带头节点链表

带头节点链表(初始化,插入,删除,查找,显示,毁链)

#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;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值