头插法建立链表

#include <stdio.h>
#include <stdlib.h>


typedef int elementype;
struct node
{
    elementype data;
    struct node *next;
};
typedef struct node linkList;


linkList *createLinkList()
{
    elementype x;
    linkList *head,*p;
    head = (linkList*)malloc(sizeof(linkList));
    head->next = NULL;
    printf("请输入数据直到输入0结束:\n");
    scanf("%d",&x);
    while(x!=0)
    {
        p = (linkList *)malloc(sizeof(linkList));
        p->data = x;
        p->next = head->next;
        head->next = p;
        scanf("%d",&x);
    }
    return (head);
}

void printLinkList(linkList *head)
{
    linkList *p = head->next;
    while(p!=NULL)
    {
        printf("%d   ",p->data);
        p = p->next;
    }
}

int main()
{
    linkList *head = createLinkList();
    printLinkList(head);
    return 0;
}

上面的程序实现了建立链表并且从头遍历链表的功能。

其实一直在疑惑一个问题

自然链表的建立有头插法和尾插法两种,区别是初始化数据的顺序是不同的。

typedef

typedef声明,简称typedef,为现有类型创建一个新的名字,或称为类型别名,在 结构体定义,还有一些 数组等地方都大量的用到。
它有助于创建平台无关类型,甚至能隐藏复杂和难以理解的语法 。使用typedef可编写出更加美观和可读的代码。所谓美观,意指typedef能隐藏笨拙的语法构造以及平台相关的 数据类型,从而增强可移植性以及未来的可维护性。

一直不太理解结构体的用法。
struct node
{
int a;
       int  b; 
};
在C语言当中,单独使用node是错误的,只有struct node 一起使用才可以当做一个新的定义的变量
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int a;
    int b;
};

int main()
{
    struct node a;
    printf("Hello world!\n");
    return 0;
}

上面是一段C语言的代码,当然我们可以通过
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int a;
    int b;
}node;

int main()
{
    node a;
    printf("Hello world!\n");
    return 0;
}

精简代码。
而在C++当中
#include <iostream>

using namespace std;
struct node
{
    int a;
    int b;
}hehe;
int main()
{
    node one;
    struct node two;
    hehe.a = 10;
    cout <<hehe.a<< endl;
    return 0;
}

以上代码定义了struct node(node)这个数据类型 并且在定义数据类型的时候生成了一个实例hehe
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int a;
    int b;
}hehe[10];

int main()
{
    hehe[1].a =10;
    printf("%d\n",hehe[1].a);
    return 0;
}

当然在C语言当中也是可以的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值