回 帖 发 新 帖 刷新版面

主题:链表

/* Note:Your choice is C IDE */
#include "stdio.h"
#include "stdlib.h"
typedef struct lst
{
    struct lst *next;
    int data;
}Lst;

//初始化
Lst *initialize(){
    Lst *head=NULL;
    head=(Lst *)malloc(sizeof(Lst));
    head->next=NULL;
    return head;
}


//输出
void outLst(Lst *head)
{
    Lst *q;
    q=head;
    do
    {
        q=q->next;
        printf("%d->",q->data);
    }while(q->next==NULL);
}


//输入
void inLst(Lst *head,int m)
{
    Lst *q=NULL;
    Lst *n=NULL;
    n=(Lst *)malloc(sizeof(Lst));
    n->data=m;
    q=head;
    while(q->next!=NULL)
    {
        q=q->next;
    }
    q->next=n;
}

void main()
{
    Lst *head;
    int d;
    head=initialize();
    scanf("%d",&d);
    while(d!=-1)
    {
        inLst(head,d);
        scanf("%d",&d);
    };


    outLst(head);
   
}



请问各位大侠,哪里错了,刚输入两个数据就出错了.....

回复列表 (共2个回复)

沙发

这里有两处需要注意下:
1、由于“笔误”,输出函数中应为while(q->next != NULL);
2、inLst函数中在n->data = m;之后加一句n->next = NULL;

板凳

#include<stdio.h>
#include<stdlib.h>

struct lst
{
    int data;
    struct lst *next;
};

int main()
{
    struct lst *q;
    struct lst *head;
    int d,m;
    q=(struct lst *)malloc(sizeof(struct lst));
    if(!q)
    {
             printf("cannot open memory.\n");
             exit(1);
    }
    
    q=head;
    for(d=0;d<=4;d++)
    {
        scanf("%d",&m);
        q->data=m;
        q->next=(struct lst *)malloc(sizeof(struct lst));
        if(d==4) q->next=NULL;
        else q=q->next;
    }
    q=head;
    while(q)
    {
        printf("%d\n",q->data);
        q=q->next;
    }
    system("pause");
    return 0;
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册