建立链表(尾接法)

//对指针还是很不熟悉 得强化
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
    int data;
    struct Node *next;
}Node;
Node* CreateLinkList(int q)
{
    int flag=0,i,d,jishu=0;
    Node *root,*e,*tree;
    for(i=1;i<=q;i++)
    {
        scanf("%d",&d);
        if(!flag)
        {
            root=(Node*)malloc(sizeof(Node));
            root->data=d;
            root->next=NULL;
            tree=root;     //建立了一个头节点
            flag=1;
        }
        else
        {
            e=(Node*)malloc(sizeof(Node));
            e->data=d;
            e->next=NULL;
            tree->next=e;   //把e节点连接到tree后面
            tree=e;  //数的最后面为新加的节点
        }
    }
    return root;
}
void PrintLinkList(Node *head)
{
    int flag = 0;
    Node *p = head, *q;
    while(p)
    {
        if(flag)
            printf(" ");
        flag = 1;
        printf("%d", p->data);
        q = p;
        p = p->next;
        free(q);
    }
}
int main()
{
    int n;
    scanf("%d", &n);
    Node *h = CreateLinkList(n);
    PrintLinkList(h);
    return 0;
}
posted @ 2019-03-04 21:07  厂长在线养猪  Views(342)  Comments(0Edit  收藏  举报