注册 登录
编程论坛 C++教室

为什么链表不能输出????

hy247767221 发布于 2011-09-18 19:51, 602 次点击
#include<stdio.h>
#include<stdlib.h>

typedef struct Node
{
    int data;
    struct Node *next;
}Node, *LNode;

LNode In_link(LNode head);
void Display_link(LNode head);
void Free_link(LNode head);

int main()
{
    LNode head = NULL, top = NULL;

    head = In_link(head);
    Display_link(head);
    putchar(10);

    top = In_link(top);
    Display_link(top);
    putchar(10);

    Free_link(head);
    Free_link(top);

    return 0;
}

LNode In_link(LNode head)
{
    int num;
    Node *link = NULL, *incept_link = NULL;

    printf("Please input the number:");
    scanf("%d", &num);
    while(num)
    {
        link = (Node *)malloc(sizeof(Node));
        link->data = num;
        if(head == NULL)
            head = link;
        else
            incept_link->next = link;
        incept_link = link;
        scanf("&d", &num);
    }
    if(incept_link != NULL)
        incept_link->next = NULL;
 
    return head;
}

void Display_link(LNode head)
{
    Node *incept_link = NULL;

    if(head == NULL)
    {
        printf("The link is empty!\n");
        return;
    }

    incept_link = head;
    while(incept_link)
    {
        printf("%3d", incept_link->data);
        incept_link = incept_link->next;
    }
}

void Free_link(LNode head)
{
    if(head == NULL)
    {
        printf("The link is empty!\n");
        return;
    }

    if(head->next)
        Free_link(head->next);
    Free_link(head);
}
7 回复
#2
玩出来的代码2011-09-18 21:33
你自己找,自己调试,看到哪停了、、
#3
nicum2011-09-19 09:10
void Free_link(LNode head)                   //假设head!=NULL,head->next=NULL
{
    if(head == NULL)                        //false
    {
        printf("The link is empty!\n");
        return;
    }

    if(head->next)                           //false
        Free_link(head->next);
    Free_link(head);                        //无穷递归
}
#4
nicum2011-09-19 09:16
void Free_link(LNode head)
{
    LNode *p=head;
    if(!p)
        return;
    head=head->next;
    delete p;
    Free_link(head);
}
#5
hy2477672212011-09-19 14:49
回复 3楼 nicum
不会啊,这不是无穷递归啊,以前有试过的··
#6
hy2477672212011-09-19 15:53
回复 5楼 hy247767221
楼上的哥们,表示抱歉,我犯了低级错误,格式控制符打错了
 scanf("&d", &num);
请原谅啦
其他的没有错误!!!
#7
nicum2011-09-19 17:40
回复 6楼 hy247767221
你看一下 当 head!=NULL  head->next=NULL 的时候 他 是不是 无穷递归
虽然 大多数 情况下 貌似没错。 但 用上面条件时 就错了。
#8
hy2477672212011-09-19 19:43
回复 7楼 nicum
恩,对了,应该是这样的
void Free_link(LNode head)
{
    if(head == NULL)
    {
        printf("The link is empty!\n");
        return;
    }

    if(head->next)
        Free_link(head->next);
    free(head);
}
谢谢你啦,是我疏忽了,以后多交流!!!
1