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

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

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

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

代码;

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

结果:

嵌入式linux-C语言学习-链表2_第1张图片

 

你可能感兴趣的:(嵌入式Linux学习,linux,c语言,学习)