我正在尝试打印双向链接循环列表的值,但我的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);
}
}
我的添加功能将节点添加到列表的最末端,当我输出列表计数
时printf("people count: %d", people->count);
它显示了添加到列表中的项目数,但是当我尝试打印出单个项目时,
printAll(people);
它不会超越第一个节点。有没有人经历过类似的事情?
答案 0 :(得分:1)
在add()
函数中,存在无法正确创建列表的问题。
list->head->prev = newC; //sets head->prev to newC
newC->prev = list->head->prev; //here setting newC->prev to head->prev which is NewC
newC->prev->next = newC; //here newC->prev->next is actually newC->next is set to newC
尝试使用gdb或其他调试器验证您的逻辑。
答案 1 :(得分:0)
在添加功能中尝试使用此逻辑。我认为它应该有用。
if(newC){
if(list->head == NULL){
list->head = newC;
}else{
newC->next = list->head;
newC->prev = list->head->prev;
list->head->prev->next = newC;
list->head->prev = newC;
}
list->count++;
}
最好尝试使用GDB
,或者如果您想了解逻辑,可以先使用图表。