【发布时间】:2014-05-15 13:13:42
【问题描述】:
我正在尝试打印出双向循环列表的值,但我的 printAll 函数出于某种原因仅打印出第一个节点的内容。
#include<stdlib.h>
#include<stdio.h>
struct clientsOn
{
int id;
char filename[20];
struct clientsOn* next;
struct clientsOn* prev;
};
struct clientsList
{
int count;
struct clientsOn* head;
};
void printAll(struct clientsList* list);
void add(struct clientsList *list,struct clientsOn *newC);
struct clientsList* createList();
struct clientsOn* createNode(char* profile);
main()
{
struct clientsList* people = malloc(sizeof(struct clientsList));
people = createList();
printf("Number of people currently on: %d\n",people->count);
struct clientsOn* pers1, *pers2, *pers3;
char boy[20],boy2[20],boy3[20];
printf("String: \n");
scanf("%s",boy);
printf("String: \n");
scanf("%s",boy2);
printf("String: \n");
scanf("%s",boy3);
pers1 = createNode(boy);
pers2 = createNode(boy2);
pers3 = createNode(boy3);
add(people,pers1);
add(people,pers2);
add(people,pers3);
printf("people count: %d", people->count);
printAll(people);
}
struct clientsList* createList()
{
struct clientsList* list = malloc(sizeof(struct clientsList));
if(list){
list->head = NULL;
list->count = 0;
}
return list;
}
struct clientsOn* createNode(char* profile)
{
struct clientsOn* clients = malloc(sizeof(struct clientsOn));
if(clients){
clients->next = clients;
clients->prev = clients;
strcpy(clients->filename,profile);
}
return clients;
}
void add(struct clientsList *list,struct clientsOn *newC)
{
if(newC){
if(list->head == NULL){
list->head = newC;
}else{
list->head->prev = newC;
newC->prev = list->head->prev;
newC->prev->next = newC;
newC->next = list->head;
}
list->count++;
}
}
void printAll(struct clientsList* list)
{
struct clientsOn* node = list->head;
if(node != NULL){
do{
printf("list content is: %s",node->filename);
node = node->next;
}while(node!=list->head);
}
}
我的 add 函数将节点添加到列表的最后,当我输出列表计数时
printf("people count: %d", people->count);
它显示了添加到列表中的项目数,但是当我尝试打印出单个项目时,
printAll(people);
它不会超出第一个节点。有人遇到过类似的事情吗?
【问题讨论】:
-
“它不会超越......曾经经历过类似的事情”是的,有点像在和小马玩耍时......;-)
标签: c doubly-linked-list circular-list