链表知识技巧

来源:互联网 发布:js字符串特殊字符转义 编辑:程序博客网 时间:2024/05/19 18:11

一、创建单向链表,链表的每个结点有一个数据元素。从键盘输入若干个非零整数作为结点的数据元素

分析:
1.为简化链表操作中对表中有结点的情况处理,一般会在链表中在链表中增加一个结点,作为链表的第一结点,但该结点不放数据元素,特称之为头结点。
2.建立一个有头结点的单向链表,采用每次在链表的尾部增加一个结点的方式,将所有的结点链接起来。由于新结点是添加在单向链表的尾部,故需要设置一个指向表尾的指针变量q,且填添加一个新结点就要更新此新指针。

# include <stdio.h># include <stdlib.h># include <malloc.h>struct Lnode{    int data;    struct Lnode*next;}*p,*q,*head; //*p为跟踪表的指针,q为指向新结点的指针,head是指向头结点的指针main(){    int temp;    head=(struct Lnode*)malloc(sizeof(struct Lnode));    if(head==NULL)    {        printf("memonry allocating error!");        exit(0);    }    head->next=NULL;    p=head;    printf("input a integer:");    scanf("%d",&temp);    while(temp!=0)    {        q=(struct Lnode*)malloc(sizeof(struct Lnode));        if(q=NULL)        {            printf("memory allocating error!");            exit(0);        }        q->data=temp;        q->next=NULL;        p->next=q;        p=q;        printf("input a integer:");        scanf("%d",&temp);    }    return 0;}

如果链表数据的顺序正好与输入的顺序一致,则可以把新结点添加在链表的头部,这样就不需要跟踪表尾指针,新建链表的效率更高。
代码如下:

# include <stdio.h># include <stdlib.h># include <malloc.h>struct Lnode{    int data;    struct Lnode*next;}*p,*q,*head; //*p为跟踪表的指针,q为指向新结点的指针,head是指向头结点的指针main(){    int temp;    head=(struct Lnode*)malloc(sizeof(struct Lnode));    if(head==NULL)    {        printf("memonry allocating error!");        exit(0);    }    head->next=NULL;    p=head;    printf("input a integer:");    scanf("%d",&temp);    while(temp!=0)    {        q=(struct Lnode*)malloc(sizeof(struct Lnode));        if(q=NULL)        {            printf("memory allocating error!");            exit(0);        }        q->data=temp;        q->next=head->next;        head->next=q;        printf("input a integer:");        scanf("%d",&temp);    }    return 0;}
原创粉丝点击