C语言实现单链表

#include <stdio.h>
#include <stdlib.h>

typedef int item_type;

typedef struct _node{
	item_type data;
	struct _node *next;
}Node, List;

/*头插法,传入指向首元素地址的指针和要插入的元素*/
void insert_list(List **pList, item_type x){
	Node *temp;
	temp = (Node *)malloc(sizeof(Node));
	
	temp->data = x;		/*填充新结点*/
	temp->next = *pList;
	*pList = temp;		/*更新首元素地址*/
}

/*递归搜索元素*/
List *search_list(List *l, item_type x){
	if(l == NULL)
		return NULL;
	
	if(l->data == x)
		return l;
	else
		return search_list(l->next, x);
}

/*递归找出元素的前驱*/
List *previous_list(List *l, item_type x){
	if(l == NULL || l->next == NULL){
		printf("Error: previous sought no null list.\n");
		return NULL;
	}

	if((l->next)->data == x)
		return l;
	else
		return previous_list(l->next, x);
}

/*删除元素,必须先找出前驱*/
void delete_data(List **pList, item_type x){
	List *p;	/*指向待删除项的指针*/
	List *pred;	/*前驱指针*/

	p = search_list(*pList, x);
	if(p != NULL){
		pred = previous_list(*pList, x);
		if(pred == NULL)	//关键,如果删的是首元素!
			*pList = p->next;
		else
			pred->next = p->next;
	}
	free(p);
}

/*打印列表*/
void print_list(List *l){
	if(l == NULL){
		puts("Print list error!");
		return;
	}
	while(l != NULL){
		printf("%d ", l->data);
		l = l->next;
	}
	putchar('\n');
}

/*销毁链表*/
void delete_list(List **pHead){
	Node *p, *tmp;

	p = (*pHead);	//p是首元素地址
	pHead = NULL;	//把头指针设置为NULL
	while(p != NULL){
		tmp = p->next;
		free(p);
		p = tmp;
	}
}

int main(){
    int i;
	List *pList = NULL;
	List **pHead = &pList;

    for(i = 1; i < 10; ++i)
        insert_list(&pList, i*4);

	//List *pred = previous_list(pList, 36);
	//if(pred == NULL)
	//	puts("yes");
	//else
	//	puts("no");

	print_list(pList);
	delete_data(&pList, 4);
    print_list(pList);
    delete_list(pHead);
    return 0;
}

 

转载于:https://www.cnblogs.com/mocuishle/p/8035262.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值