如何为链表调试此代码?

时间:2017-12-14 11:47:00

标签: c

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

#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");
}

1 个答案:

答案 0 :(得分:1)

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

/* 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)