c语言动态链表创建

公共代码块 

#include <stdio.h>
#include <stdlib.h>
struct Test{
        int num;
        struct Test *next;
}; //创建结构体

void listLink(struct Test *head)
{
        while(head!=NULL)
        {
            printf("%d ",head->num);
            head=head->next;
        }
        putchar('\n');
} //列出结构体中的数据的函数

头插法创建添加动态链表 

/*insert head 头插法*/ 
struct Test *insertHead(struct Test *head,struct Test *new)
{
        if(head==NULL) //头节点都没有,那新的就是头节点
        {
          head=new;
          return head;
        }
         else   //否则新的就会被替换为头节点
        {
          new->next = head;
          head = new;
        }
        return head;
}

struct Test *createLink(struct Test *head) //创建链表,并使用头插法方式
{
    struct Test *new;
   while(1){
        new = (struct Test*)malloc(sizeof(struct Test));
        new->next=NULL;
        printf("Please input num:");
        scanf("%d",&(new->num));
        if(new->num ==0)
        {
            printf("Quit!\n");
            free(new);
            return head;
        }else{
           head = insertHead(head,new);
             }
           }
}

int main()
{
   struct Test *head = NULL; //初始化头节点
   head = createLink(head); //使用头插法创建链表
   listLink(head); //列出链表所有的数据

   return 0;
}

 运行结果

 

 

尾插法创建添加动态链表 

 

/*insert tail*/
struct Test *inserttail(struct Test *head,struct Test *new)
{
        struct Test *p=head; //存放链表头
        if(p==NULL) //如果链表什么都没有,新的就是头节点
        {
          head=new;
          return head;
        }
         while(p->next!=NULL) //一直找到链表尾
             {
                p=p->next;
             }
             p->next = new;//链表尾指向新节点
        return head; //没有改变头节点,所以返回head就行了
}
struct Test *createLink(struct Test *head)//以尾插法方式创建链表
{
    struct Test *new;
   while(1){
        new = (struct Test*)malloc(sizeof(struct Test));
        new->next=NULL;
        printf("Please input num:");
        scanf("%d",&(new->num));
        if(new->num ==0)
        {
            printf("Quit!\n");
            free(new);
            return head;
        }else{
           head = inserttail(head,new);
             }
           }
}

运行结果 

 

 

 当然你想手动添加也是行的!

 

int main()
{
   struct Test *head = NULL;
   head = createLink(head);
   listLink(head);
   struct Test t1={88,NULL};
   head = inserttail(head,&t1);
   listLink(head);
   return 0;
}

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值