头插法建立链表

来源:互联网 发布:linux 网桥 问题 编辑:程序博客网 时间:2024/05/22 04:24
#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语言当中也是可以的