关于C语言中链表声明中结构体的使用方法


typedef struct _node{

    int data;

    struct _node * next;

};

//尾插法:创建一个递增有序的单链表

_node* last_create()

{

    _node *head = (_node*)malloc(sizeof(_node));

    head->data = 10;//带头结点,头结点data存链表长度

    //head->next = NULL;//头结点next指向NULL

    _node *last=head;

    for(int i=1;i<11;i++)

    {

           _node *p = (_node*)malloc(sizeof(_node));

           p->data = i;

           p->next = NULL;

           last->next = p;

           last = last->next;

    }

    return head;

}





//按顺序打印整个链表

bool printlist(_node* list)

{

    if(list==NULL)

           return false;

    else

    {

           _node* p = list->next;//直接从头结点后面一个节点开始访问,因为头结点存的是长度

           while(p!=NULL)

           {

                  printf("%d\n",p->data);

                  p = p->next;

           }

           return true;

    }

}



int main()

{

    _node *head = last_create();

    printlist(head);

    return 0;

}

编译成功!

 


#include<stdio.h>

#include<stdlib.h>

typedef struct _node{

    int data;

    struct _node * next;

}Node;

/*

自动生成(1,2,3,4,5,6,7,8,9,10)链表

*/



//尾插法:创建一个递增有序的单链表

Node* last_create()

{

    Node *head = (Node*)malloc(sizeof(Node));

    head->data = 10;//带头结点,头结点data存链表长度

    //head->next = NULL;//头结点next指向NULL

    Node *last=head;

    for(int i=1;i<11;i++)

    {

           Node *p = (Node*)malloc(sizeof(Node));

           p->data = i;

           p->next = NULL;

           last->next = p;

           last = last->next;

    }

    return head;

}

//按顺序打印整个链表

bool printlist(Node* list)

{

    if(list==NULL)

           return false;

    else

    {

           Node* p = list->next;//直接从头结点后面一个节点开始访问,因为头结点存的是长度

           while(p!=NULL)

           {

                  printf("%d\n",p->data);

                  p = p->next;

           }

           return true;

    }

}



int main()

{

    Node *head = last_create();

    printlist(head);

    return 0;

}

编译成功!

 

 

  • 总结:typedef主要是省去之后每次创建Node时都要struct Node的麻烦。但是在节点类型声明中next域还是要用struct 来声明,因为此时typedef还没生效,要typedef那个结构体声明块}结尾后才生效。}之后起的是结构体的别名,第一种方案中没有起别名,直接_node也是成功编译的。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值