嵌入式linux-C语言学习-链表2

实现:链表头插法,尾插法,删除

注意:结构体中,辅助指针p的作用,head指针必须一直指向链表第一个节点。

尾插法的链表:不输入0,一直循环,head2一直加节点在while循环中,知道输入0,直接结束循环。

代码;

#include <stdio.h>
#include <stdlib.h>
struct node 
{
	int data;
	struct node *next;
	
};

void printnode(struct node *head)
{
   
    while(head!=NULL){
        //if(head!=NULL){
             printf("%d ",head->data);
             head=head->next;
       // }
           
    }
    putchar('\n');
}


struct node *InsertFromHead(struct node *head,struct node *new)
{
	
	if(head == NULL){
		head = new;
		return head;
	}else{
	new->next=head;//将new节点连接起来
	head=new;
	}
	return head;
}
//头插法
struct node *CreatLink(struct node *head2)
{
	struct node *new4;

	while(1){
		new4=(struct node *)malloc(sizeof(struct node));
		puts("请输入创建头插法链表的数据按0结束");
	    scanf("%d",&(new4->data));
		new4->next=NULL;//必须加上
		if(new4->data == 0){
			
			puts("结束");
			free(new4);
			return head2;
			
		}
		head2 = InsertFromHead(head2,new4);
	}
	
}
//尾插法

struct node *InsertFromlast(struct node *head,struct node *new)
{
	struct node *p=head;
	if(head==NULL){
		head=new;
		return head;
		
	}
	while(p->next!=NULL){
		p=p->next;
	}
	p->next=new;//确定了head的next连接了new,形成了一个链表
	return head;
}
struct node *CreatLink2(struct node *head2)
{
	struct node *new4;

	while(1){
		new4=(struct node *)malloc(sizeof(struct node));
		puts("请输入创建尾插法插法链表的数据按0结束");
	    scanf("%d",&(new4->data));
		new4->next=NULL;//必须加上
		if(new4->data == 0){
			
			puts("结束");
			free(new4);
			return head2;
			
		}
		head2 = InsertFromlast(head2,new4);
	}
	
}
//删除数据
struct node *deletenode (struct node *head,int data)
{
	puts("请输入删除的数据");
	 scanf("%d",&data);
	struct node *p=head;//注意头的问题,要确保,head每次都是指向链表的第一个地址,所以用辅助指针p
	 if(p->data==data){//头是否相等
		 head=head->next;
		 
	 }else{
	 for(;p->next!= NULL;p=p->next){//此时head还是头地址,但是p地址随着循环改变
		 if(p->next->data==data){
			 p->next=p->next->next;
			 return head;
		 }
		 
		 
	 }
	 }
	 return head;
	
	
}
int main()
{
	int data =0;
	struct node *head2=NULL;
	head2=CreatLink(head2);
	printnode(head2);
	head2=NULL;
	head2=CreatLink2(head2);
	printnode(head2);
	head2=deletenode(head2,data);
	printnode(head2);
	return 0;
 }

结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值