TZOJ 数据结构实验:创建单链表

描述

实现一个函数CreateLinkList,能够完成不带头节点链表的创建。

部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

 

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;
}

输入

输入n和n个节点元素值

输出

输出节点值并清空链表。 

样例输入

 3

 1 2 3

样例输出

 1 2 3

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
}Node;
Node* CreateLinkList(int n)
{
    Node *head,*p,*bao;
    bao=(Node*)malloc(sizeof(Node));
    scanf("%d",&bao->data);
    bao->next=NULL;
    head=bao;
    for(int i=1;i<n;i++)
    {
        p=(Node*)malloc(sizeof(Node));
        scanf("%d",&p->data);
        p->next=NULL;
        bao->next=p;
        bao=p;
    }
    return (head);
}
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 @ 2018-03-28 21:42  极限之旅  阅读(1082)  评论(0编辑  收藏  举报