创建链表

数据结构之创建链表

数据结构中经常用到结构体struct,它用起来比较麻烦,这是会用到typedef来起别名

C语言给结构体定义别名用typedef关键字操作,就两种情况:
给结构体起一个别名,如:
typedef struct ABC{…
}S;——这就为结构体ABC定义了一个别名S。以后写S x;就等价于写struct ABC x;了。
给结构体指针起一个别名,如:
typedef struct ABC{

}*PS;——这就为结构体指针ABC *定义了一个别名PS。以后写PS pt;就等价于写struct ABC pt;了。注意这里是用typedef给struct ABC{…} 起一个别名PS,而不是给struct ABC{…}起一个别名PS——后者是说不通的,起码的错误是标识符不可能以开头!

我们接着来看一段我写的代码:

#include <iostream>

using namespace std;
typedef struct node
{
    int data;
    struct node *next;
}node,*linklist;
linklist create(int n){
    linklist head;//node *head
    head = new node;
    head->next=NULL;
    linklist tail;
    tail=new node;
    tail=head;

    for(int i=0;i<n;i++){
        int x;
        scanf("%d",&x);
        linklist p = new node;
        p->data=x;
        tail->next=p;
        tail=p;
        p->next=NULL;
    }
    return head;
}
void printlist(linklist head){
    linklist p;
    p=new node;
    p=head->next;
    while(p){
        printf("%d,",p->data);
        p=p->next;
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    linklist head;
    head=create(n);
    printlist(head);
    return 0;
}

这里使用了尾插法
来大致浏览一下代码:

typedef struct node
    {
        int data;
        struct node *next;
    }node,*linklist;

给结构体struct node起别名–node以及指针别名linklist

 linklist create(int n){
    linklist head;//node *head
    head = new node;
    head->next=NULL;
    linklist tail;
    tail=new node;
    tail=head;

    for(int i=0;i<n;i++){
        int x;
        scanf("%d",&x);
        linklist p = new node;
        p->data=x;
        tail->next=p;
        tail=p;
        p->next=NULL;
    }
    return head;
}
一个类型为前面定义的结构体名字叫create的函数,传入n这个参数
创建头节点,头节点指针为空
创建尾节点,尾节点和头指针相等
for循环
输入一个数据x
创建一个新的节点
新节点的数据赋值为x
将新定义的节点连接到尾节点上
将p覆盖为新的尾节点
尾节点的指针为空
返回头指针


  void printlist(linklist head){
    linklist p;
    p=new node;
    p=head->next;
    while(p){
        printf("%d,",p->data);
        p=p->next;
    }
}

输出函数,引入头节点
创建新的p节点
p指向头节点的下一个节点
当p不为NULL时一直往屏幕打印data
并将p指向下一个节点

 int main()
    {
        int n;
        scanf("%d",&n);
        linklist head;
        head=create(n);
        printlist(head);
        return 0;
    }

主函数入口
定义需要的节点数并输入
/*不是很懂
创建头节点的指针

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值