gpt4 book ai didi

c - 如何调试链表的这段代码?

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

我写这个是为了在链表上执行推送和反向操作,但推送/反向功能无法正常工作。我不知道问题出在哪里,一切似乎都很好。有人可以帮我吗?我认为链表的头或函数的参数有问题。我需要声明一个指向指针的指针作为参数吗?

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
struct node {
int data;
struct node *next;
};
typedef struct node NODE;
NODE *head1 = NULL;
int flag = 1;
int choice;

void push(NODE*);
void menu();
void reverse(NODE*);
void display(NODE*);

int main() {
do {
menu();
if (choice == 1) {
push(head1);
display(head1);
}
else if (choice == 2) {
reverse(head1);
display(head1);
}
else {
break;
}
} while (1);


}

void push(NODE *head) { //function to create the linked list
int choice1, flag = 1;
do {
NODE *new_node = (NODE*)malloc(sizeof(NODE*));
puts("Enter new node data:");
scanf("%d", &new_node->data);
if (!head) {
head = new_node;
head->next = NULL;
}
else {
new_node->next = head;
head = new_node;
}
puts("Do you want to continue? Press 1:");
fflush(stdin);
scanf("%d", &choice1);
if (choice1 != 1) {
flag = 0;
}
} while (flag);
}

void menu() {
puts("Enter 1 to push, 2 to reverse, anything else to exit:");
scanf("%d", &choice);
}

void reverse(NODE *head) { //function to reverse it
NODE *prev = NULL, *next = NULL;
NODE *current = head;
while (current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}

void display(NODE *head) {
NODE *temp = head;
puts("Status of the linked list:");
for (; temp; temp = temp->next) {
printf("%d=> ", temp->data);
}
puts("NULL");
}

最佳答案

这段代码有很多问题。我将从一个小片段开始。

/* global */
NODE *head1 = NULL;

/* in main */
push(head1);

void push(NODE *head) { //function to create the linked list
int choice1, flag = 1;
do {
NODE *new_node = (NODE*)malloc(sizeof(NODE*));
puts("Enter new node data:");
scanf("%d", &new_node->data);
if (!head) {
head = new_node;
head->next = NULL;
}

push() 正在获取一个指向 NODE 的指针,分配一些内容,然后将其分配给该指针。 这只修改了push()中指针的本地副本,而head1保持不变。要修改 head1,您需要返回一个指针或获取一个指向指针的指针。

那就是

void push(NODE** head)

NODE* push(NODE* head)

head1 = push(head1);

您还分配了sizeof(NODE*),即指针的大小(通常为 8 或 4 字节)。这应该是sizeof(NODE)

关于c - 如何调试链表的这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812611/

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