这是个简易链表,我依次输入1 2 3但是最后只会输出1,并且输出1后,Node* p就会指向NULL,我不理解为什么会这样,请各位帮我看看
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int value;
struct _node* next;
}Node;
typedef struct {
Node* head;
}List;
void add(List* plist, int number);
int main(int argc, char* argv[])
{
List list;
list.head=NULL;
int number;
do {
scanf("%d", &number);
add(&list, number);
} while (number != -1);
Node*p;
for(p=list.head;p;p=p->next){
printf("p=%d\n",p->value);
}
return 0;
}
void add(List* plist, int number)
{
if (number != -1)
{
Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next=NULL;
Node* last = plist->head;
if (last)
{
while (last->next) {
last = last->next;
last->next = p;
}
}else {
plist->head = p;
}
}
}
你的第33到36行,判断头指针存不存在,只有第一次添加链表时将1加了上去,后面的2,3由于last存在,所以进入第一个if(last),在判断while时,last->next肯定不存在。建议你把第38行放到while循环外面。
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int value;
struct _node* next;
}Node;
typedef struct {
Node* head;
}List;
void add(List* plist, int number);
int main(int argc, char* argv[])
{
List list;
list.head=NULL;
int number;
do {
scanf("%d", &number);
add(&list, number);
} while (number != -1);
Node*p;
for(p=list.head;p;p=p->next){
printf("p=%d\n",p->value);
}
while (p)
{
Node *q = p;
p = p->next;
free(q);
}
return 0;
}
void add(List* plist, int number)
{
if (number != -1)
{
Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next=NULL;
Node* last = plist->head;
if (last)
{
while (last->next) {
last = last->next;}
last->next = p;
}else {
plist->head = p;
}
}
}
帮你改好了
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
int value;
struct _node *next;
} Node;
typedef struct
{
Node *head;
} List;
void add(List *plist, int number);
void destroy(List *pList);
int main(int argc, char *argv[])
{
List list;
list.head = NULL;
int number;
do
{
scanf("%d", &number);
add(&list, number);
} while (number != -1);
Node *p;
for (p = list.head; p; p = p->next)
printf("p=%d\n", p->value);
destroy(&list);
return 0;
}
void add(List *plist, int number)
{
if (number != -1)
{
Node *p = (Node *)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
Node *last = plist->head;
if (last)
{
while (last->next)
last = last->next;
last->next = p;
}
else
{
plist->head = p;
}
}
}
void destroy(List *pList)
{
Node *p = pList->head;
while (p)
{
Node *q = p;
p = p->next;
free(q);
}
}