链表及其各种操作

1. 链表的定义

 

2.单链表的定义

typedef struct node{
    data_t data; //结点的数据域
    struct node*next;//结点后继指针域
}listnode,*linklist;
//listnode A;
//linklist p = &A; 只是在栈上申请内存空间
//获取第一个/二个元素的数据   p->data; p->next->data;
//若指针p的值为NULL,则它不指向任何结点, 此时取p->data或p->next是错误的(段错误)

3. 单链表的实现

linklist list_create(){
	linklist H = (linklist)malloc(sizeof(listnode));
	if(H==NULL){
		printf("malloc failed\n");
		return NULL;
	}
	H->data = 0;
	H->next = NULL;
	return H;
}

int list_tail_insert(linklist H,data_t value){
	//1 new node
	linklist p ;
	linklist q ;
	if(H==NULL){
		printf("H is NULL\n");
		return -1;
	}	
	if((p=(linklist)malloc(sizeof(listnode)))==NULL)
	{
		printf("malloc failed\n");
		return -1;
	}
	p->data = value;
	p->next = NULL;
	//2 locate tail node
	q = H;
	while(q->next!=NULL){
		q = q->next;
	}
	//3 insert
	q->next = p;
	return 0;
}

linklist list_get(linklist H,int pos){
	linklist p;
	int i=0;
	if(H == NULL){
		printf("H is NULL\n");
		return NULL;
	}
	if(pos == -1){
		return H;
	}
	p = H;
	while(i<=pos){   //loop pos+1 times
		p = p->next;
		if(p == NULL){ //exceed max pos
			printf("pos is invalid\n");
			return NULL;
		}
		i++;
	}
	return p;
}

int  list_insert(linklist H,data_t value,int pos){
	linklist p;
	linklist q;

	if(H == NULL){
		printf("H is NULL\n");
		return -1;
	}

	//1 locate node p (pos-1)
	p = list_get(H,pos-1);
	if(p == NULL){
		return -1;
	}

	//2 new node q
	if((q=(linklist)malloc(sizeof(listnode)))==NULL){
			printf("malloc failed\n");
			return -1;
	}

	q->data = value;
	q->next = NULL;

	//3 insert
	q->next = p->next;
	p->next = q;

	return 0;
}

int list_show(linklist H){

	linklist p;
	if(H == NULL){
		printf("H is NULL\n");
		return -1;
	}
	p = H;

	while(p->next !=NULL){
		printf("%d ",p->next->data);
		p = p->next;
	}
	puts("");

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值