c语言(链表)

链表比数组的优点是,方便增删;因为数组中的元素都是连续的,增删起来非常不便。

#include <stdio.h>

struct Students
{
        int score;
        struct Students *p;
};

int main()
{
        struct Students stu1 = {29,NULL};
        struct Students stu2 = {69,NULL};
        struct Students stu3 = {36,NULL};

        stu1.p = &stu2;
        stu2.p = &stu3;

        printf("stu1 = %d,stu2 = %d,stu3 = %d\n",stu1.score,stu1.p->score,stu1.p->p->score);
        return 0;
}

链表的增、查询,节点后、后插入新元素

#include <stdio.h>

struct Students
{
	int score;
	struct Students *next;
};

void ptintlink(struct Students *p)
{
	struct Students *point;
	point = p;
	while(point != NULL)
	{
		printf("%d ",point->score);
		point = point->next;
	}
	putchar('\n');
}


int searchlink(struct Students *point,int data)
{
	struct Students *head;
	head = point;
	while(head != NULL)
	{
		if(head->score == data)
		{
			return 1;
		}
		head = head->next;
	}
	return 0;
}

struct Students *inserFromfor(struct Students *head,int data,struct Students *new)//节点前插入
{
	struct Students *point;
	point = head;
	if(point->score == data)
	{
		new->next = head;
		return new;
	}
	while(point != NULL)
	{
		if(point->next->score == data)
		{
			new->next = point->next;
			point->next = new;
			return head;
		}
		point = point->next;
	}
	return head;
}

int inserFromBehind(struct Students *head,int data,struct Students *new)//节点后插入
{
	struct Students *point;
	point = head;
	while(point != NULL)
	{
		if(point->score == data)
		{
			new->next = point->next;
			point->next = new;
			return 1;
		}
		point = point->next;
	}
	return 0;	
}



int main()
{
	struct Students *head;
	struct Students stu1 = {10,NULL};
	struct Students stu2 = {20,NULL};
	struct Students stu3 = {30,NULL};
	struct Students stu4 = {40,NULL};
	struct Students stu5 = {50,NULL};
	struct Students stu31 = {39,NULL};
	
	stu1.next = &stu2;
	stu2.next = &stu3;
	stu3.next = &stu4;
	stu4.next = &stu5;
	
	/*结点前插入
	head = &stu1;
	ptintlink(&stu1);
	putchar('\n');
	head = inserFromfor(&stu1,50,&stu31);
	ptintlink(head);*/
	

	/*节点后插入
	int ret;
	ret = inserFromBehind(&stu1,50,&stu31);
	if(ret == 1)
	{
		putchar('\n');
		ptintlink(&stu1);
		printf("已插入\n");
	}
	else
	{
		printf("没找到\n");
	}*/
	
	/*查询
	int ret;
	ret	= searchlink(&stu1,1);
	if(ret == 1)
	{
		printf("找到了\n");
	}
	else
	{
		printf("没找到\n");
	}*/
	
	return 0;
}

  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值