链表头插法和尾插法

文章目录

1.头插法

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
//==============头插法建立链表==========================
struct LNode *CreatLNode(){
    int x;
    int LNode_len=0;                          //计算链表长度
    LNode *head;
    LNode *s;
    //head->next=NULL;                          //初始为空链表
    head=(struct LNode*)malloc(sizeof(struct LNode));//创建头结点
    printf("请输入数据(9999结束)\n");
    scanf("%d",&x);
    while(x!=9999){
        s=(struct LNode*)malloc(sizeof(struct LNode));
        s->data=x;
        s->next=head->next;
        head->next=s;
        LNode_len++;
        head->data=LNode_len;
        scanf("%d",&x);
    }
    return head;
};
//==============头插法建立链表==========================



//输出
LNode print(LNode *head){
LNode *p=head->next;
int i;
for(i=0;i<head->data;i++){
     printf("%3d",p->data);
    p=p->next;

}
}
int main()
{
   LNode *p;
   p=CreatLNode();
   print(p);
    return 0;
}

在这里插入图片描述

2.尾插法

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
//==============尾插法建立链表==========================
struct LNode *CreatLNode(){
    LNode *head;    
    LNode *p1,*p2;
    int LNode_len=0;
    int x;
    head=(struct LNode*)malloc(sizeof(struct LNode));//建立头结点
    p1=p2=head;    //让p1和p2都指向头结点
    printf("请输入数据(9999结束)\n");
    scanf("%d",&x);         //输入数据
    while(x!=9999){
        p1=(struct LNode*)malloc(sizeof(struct LNode));  //再让p1建立一个新结点把x值放进去(此时头结点没有放值)
        p1->data=x;
        p2->next=p1; //p2指向p1
        p2=p1;       //p2在等于p1又使p1和p2又指向了同一个。。。重复。。。
        LNode_len++;
        head->data=LNode_len;
        scanf("%d",&x);
    }
    p1->next=NULL;
    return head;
};
//==============尾插法建立链表==========================



//输出
LNode print(LNode *head){
LNode *p=head->next;
int i;
for(i=0;i<head->data;i++){
     printf("%3d",p->data);
    p=p->next;

}
}
int main()
{
   LNode *p;
   p=CreatLNode();
   print(p);
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值