gpt4 book ai didi

c - 在c中打印双向链表的内容仅打印出第一个节点

转载 作者:行者123 更新时间:2023-11-30 20:26:52 24 4
gpt4 key购买 nike

我正在尝试打印出双向链接循环列表的值,但由于某种原因,我的 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);

它不会超出第一个节点。有人经历过类似的事情吗?

最佳答案

在您的 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 或其他调试器来验证您的逻辑。

关于c - 在c中打印双向链表的内容仅打印出第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23679349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com