gpt4 book ai didi

创建双链表问题

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

我们的任务是首先创建一个双链表,然后对其进行排序。我目前陷入第一部分。由于某种原因,直到第三个节点未创建时才添加第二个节点,并且一直持续到我输入不包括的最后一个节点,但添加了一个值为 0 的节点。

#include <stdio.h>
#include <stdlib.h>
#include "node.h"
#include "node.c"


int main(){
printf("Enter the values, once finished enter 0 to stop.\n");
int v;
scanf("%d",&v);
struct mynode headnode = {v};
struct mynode *hpoint = &headnode;
struct mynode **hpointp = &hpoint;
while (v!=0){
struct mynode *nn1 = (struct mynode*)malloc(sizeof(struct mynode));
struct mynode *endnode = *hpointp;
scanf("%d",&nn1->value); // using this because value is a constant in mynode and it wont let me write to it directly
nn1->next = NULL;
v = nn1->value;
if (v == 0){
free(nn1);
break;
}

while(endnode->next != NULL){
endnode = endnode->next;
}

endnode->next = nn1;
nn1->prev = endnode;
printlist(hpoint);
}
printlist(hpoint);

return 0;

}




here is the printlist function as well just in case i made a mistake there.


void printlist(struct mynode* n){
if (n->next == NULL && n->prev == NULL ){
printf("%d",n->value);
}

while (n->next != NULL){
printf("%d <===> ",n->value);
n = n->next;
if (n->next == NULL){
printf("%d\n",n->next);
}
}
}

最后是节点头文件

#ifndef node_h
#define node_h

struct mynode{
int const value;
struct mynode *next;
struct mynode *prev;
};

//struct mynode *insertsort(struct mynode*);

void printlist(struct mynode*);

#endif

最佳答案

你的打印功能看起来很复杂。您可以简单地循环直到 nNULL 并打印值。

void printlist(struct mynode* n){
while(n) {
printf("%d <===>",n->value);
n=n->next;
}
printf("0");
}

关于创建双链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070490/

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