读书人

!本人写了一个链表的建立与输出的程序

发布时间: 2012-03-28 15:40:03 作者: rapoo

求助!本人写了一个链表的建立与输出的程序,但一直不知道哪里出错,请高手指点迷经,,急!谢谢……
#include<stdio.h>
#include<malloc.h>

#define Element char
typedef struct Node
{
Element data;
struct Node *next;
}Node,LinkList;
void GetFromHead(LinkList L)
{
Node *s;
char c;
int flag;
flag=1;
while(flag)
{
c=getchar();
if(c!='$')
{
s=(Node*)malloc(sizeof(Node));
s->data=c;
s->next=L->next;
L->next=s;
}
else flag=0;
}

return L;
}
void main()
{
Node *H,*A,*P;
H=GetFromHead(A);
P=H;
while(P!=Null)
{
printf("%d",P->date);
P=P->next;
}
printf("\n");
}

[解决办法]
问题,不少
LinkList按照你的意思,应该定义为结构体指针才对,否则应该是用l.next,l.dat
如果用结构体指针,那么在主函数中你的A没有初始化,是个空指针
另外函数GetFromHead(LinkList L)不应该是void类型吧,或许是你笔误

[解决办法]
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>
#define Element char

typedef struct Node
{
Element data;
struct Node *next;
}*LinkList;


LinkList GetFromHead(LinkList L)
{
L=(Node*)malloc(sizeof(Node));
L->next=NULL;
Node *s;
char c;
int flag;
flag=1;
while(flag)
{
c=getchar();
if(c!='$')
{
s=(Node*)malloc(sizeof(Node));
s->data=c;
s->next=L->next;
L->next=s;
}
else flag=0;
}

return L;
}
void main()
{
LinkList H,A,P;
H=GetFromHead(A);
P=H->next;
while(P!=NULL)
{
//printf("%d",P->data);
cout<<P->data;
P=P->next;
}
//printf("\n");
cout<<endl;
}
[解决办法]

探讨

L=(Node*)malloc(sizeof(Node));
L->next=NULL;
定义L为指针变量不是已经开辟了内存单元了,为什么要用malloc开辟一个空间?直接使L->next=NULL;
为什么不行,请高手指点迷经,谢啦!

[解决办法]
C/C++ code
#include <stdio.h>#include <malloc.h>typedef struct node{    int data;    struct node *next;}linkNode, *linklist;/**功能:初始化链表*返回值:链表首地址*/linklist initList(){    linklist head;    head = (linklist)malloc(sizeof(linkNode));    if(head == NULL)        return NULL;    head->next = NULL;    return head;}/**功能:申请空间*参数:结点(数据)*返回值:指向结点的指针*/linklist makeNode(linkNode nodeData){    linklist newNode;    newNode = (linklist)malloc(sizeof(linkNode));    if(newNode == NULL)        return NULL;    newNode->data = nodeData.data;    return newNode;}/**功能:输出链表数据*参数:链表首地址*/void printList(linklist head){    if(head == NULL || head->next == NULL)        return;    head = head->next;    printf("\nlinklist:\n");    while(head != NULL)    {        printf("%d  ", head->data);        head = head->next;    }    printf("\n");}/**功能:在链表尾部插入结点*参数:链表首地址,待插入结点地址*/void pushBack(linklist head, linklist insertNode){    if(head == NULL)        return;    while(head->next != NULL)    {        head = head->next;    }    head->next = insertNode;    insertNode->next = NULL;}int main(){    linklist list, insertNode;    linkNode newNode;    int i;    list = initList();    for(i = 0; i < 10; ++i)    {        newNode.data = i;        insertNode = makeNode(newNode);                pushBack(list, insertNode);    }    printList(list);    getchar();    return 0;} 

读书人网 >C语言

热点推荐