我我不知道这是C的方式..但你必须认为你的代码如何释放你分配的指针...像自由列表功能也许..
这是我的方式。
#include<stdio.h>
#include<stdlib.h>
struct node{
char ch;
struct node *next;
};
struct node * addnode(struct node *head, struct node *p1, char ch) {
if(head==NULL) {
printf("......return 2... \r\n");
head=(struct node *)malloc(sizeof(struct node));
head->ch=ch;
head->next=NULL;
return head;
}
else {
struct node *New=NULL;
printf("......return ... \r\n");
New=(struct node *) malloc (sizeof(struct node));
New->ch = ch;
New->next=NULL;
for(p1=head;p1->next!=NULL;p1=p1->next);
p1->next=New;
return head;
}
}
void main() {
char ch,frm,to;
struct node *head=NULL, *p1=NULL;
printf("\nEnter the string \n");
while((ch=getchar())!='q')
head = addnode(head, p1, ch);
for(p1=head;p1!=NULL;p1=p1->next)
{
printf("\n%c",p1->ch);
}
}
另一个。
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char ch;
struct node *next;
} *pNODE, NODE;
pNODE addnode2(pNODE head, pNODE p1, char ch) {
if(head==NULL) {
printf("......return 2... \r\n");
head=(pNODE)malloc(sizeof(NODE));
head->ch=ch;
head->next=NULL;
return head;
}
else {
struct node *new=NULL;
printf("......return ... \r\n");
new=(pNODE) malloc (sizeof(NODE));
new->ch = ch;
new->next=NULL;
for(p1=head;p1->next!=NULL;p1=p1->next);
p1->next=new;
return head;
}
}
void main() {
char ch,frm,to;
pNODE head=NULL;
pNODE p1=NULL;
printf("\nEnter the string \n");
while((ch=getchar())!='q')
head = addnode2(head, p1, ch);
for(p1=head;p1!=NULL;p1=p1->next)
{
printf("\n%c",p1->ch);
}
}
当你分配一个新节点时,你永远不会为它分配任何值。所以'ch'将是未知的,并且'next'可能指向任何地方。 'addnode(ch)'实际上并不使用'ch'这个事实应该是一个警告信号...... – jasonharper
罗杰那,谢谢你; –