链表----C语言

本文介绍了使用C语言实现的链表尾插法创建,并演示了如何通过用户输入动态插入节点并打印链表的过程。同时,展示了两个不同场景下链表的插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

//尾插法建立链表

void ListTailInsertAndprint(LNode*l){
	int x;
	//l=(LNode*)malloc(sizeof(LNode));//建立一个头结点,但并未赋值为NULL 
	LNode*s,*r=l;                   //*s为空指针,*r指向l 
	scanf("%d",&x);
	while(x!=9999){  //数字是随机的 
	    s=(LNode*)malloc(sizeof(LNode));      //申请新空间   
		s->data=x;            //
		r->next=s;            //把头结点的next指向第二个结点的data 
		r=s;                  //把r指向第二个结点 
		scanf("%d",&x);
	}
	r->next=NULL;
	
		LNode*cur=l;
	while(cur!=NULL){
		printf("%d->",cur->data);
		cur=cur->next;
}
      printf("NULL");
}


int main(){
	LNode l;
	
	ListTailInsertAndprint(&l);
	
	return 0;
}


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

int main()
{//链表元素的输入
    struct node *head;
    struct node *p,*q,*t;
    
    int i,n,a;
    scanf("%d",&n);
    head=NULL;
    for(i=1; i<=n; i++) {
        scanf("%d",&a);
        p=(struct node*)malloc(sizeof(struct node));
        p->data=a;
        p->next=NULL;
        if(head==NULL) 
            head=p;
        else
            q->next=p;
        q=p;
    }
//链表元素的插入
    scanf("%d",&a);
    t=head;
    while(t!=0){
    if(t->next==NULL || t->next->data>a)
    {
    p=(struct node*)malloc(sizeof(struct node));
    p->data;
    p->next=t->next;
    t->next=p;
    break;
    }
    t=t->next;
    }
    
    
//输出链表所有数
    t=head;
    while(t!=NULL) {
        printf("%d",t->next);
        t=t->next;
    }


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值