数据结构1.链表的建立

        链表的建立主要是分两种,一种为头接法,一种为尾接法。头接法比较简单,但是输入和输入的循序是相反的,个人不是很喜欢。尾接法相对比较复杂,好处就是,输入输出的顺序是不变的。

        主要讲解一下尾接法。先建立结构体

struct ListNode
{
    int data;
    struct ListNode *next;
};
        尾接法的链表建立主要有3个结构体变量,这里取名为head,middel,tail。
    struct ListNode *head, *middle, *tail;
        其中head为链表的表头,他是不动的。tail为输入的结构,新输入的数据将先存在tail中。然后middle和tail地址不断的交换,已完成链表的建立,值得注意的是,链表的结尾必须是NULL。
int main()
{
    struct ListNode *head, *middle, *tail;
    int t;
    head = NULL;
    while(scanf("%d",&t) && t!=-1)//当输入为-1时结束输入
    {
        tail = (struct ListNode*)malloc(sizeof(struct ListNode));
        tail->data = t;
        if(head == NULL)
            head = tail;
        else
            middle->next = tail;
        middle = tail;
    }
    tail->next = NULL;
    while(head)
    {
        printf("%d ",head->data);
        head = head->next;
    }
    printf("\n");
}

猜你喜欢

转载自blog.csdn.net/be__yond/article/details/53240691