我我不知道這是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
羅傑那,謝謝你; –