在链表中打印最大值时输出错误

我正在用 C++ 语言打印链表的最大值。但我没有得到想要的输出。在构建和运行代码时,终端卡在构建它的过程中。我在 VS Code 和 Sublime text 中都尝试过。我正在使用 mingw64 编译器。

运行程序后出现这种情况显示链表后卡住

#include <stdlib.h>
#include <stdio.h>

using namespace std;

struct node {
    int data;
    struct node *next;
} *first = NULL;

//declaring a global head/first pointer which stores the address of first node

void create(int a[], int n) {
    int i;
    struct node *t, *last;
    first = (struct node *)malloc(sizeof(struct node));
    first->data = a[0];
    first->next = NULL;
    last = first;

    for (i = 1; i < n; i++) {
        // t = new node;
        t = (struct node *)malloc(sizeof(struct node));
        t->data = a[i];
        t->next = NULL;
        last->next = t;
        last = t;
    }
}

void display(struct node *p) {
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
}

int Max(struct node *p) {
    int max = -100;
    while (p != NULL) {
        if (p->data > max) {
            max = p->data;
            p = p->next;
        }
    }
    return max;
}

int main() {
    int m = 0;
    int a[] = { 3, 5, 7, 10, 15, 8, 12, 20 };
    create(a, 8);
    display(first);
    printf("n");
    m = Max(first);
    cout << "The maximum of the linked list is : " << m;
    return 0;
}

回答

    while (p != NULL)
    {
        if (p->data > max)
        {
            max = p->data;
            p = p->next;
        }

    }

将此更新为

    while (p != NULL)
    {
        if (p->data > max)
        {
            max = p->data;
        }
        p = p->next;
    }

否则您的代码将陷入无限循环。


以上是在链表中打印最大值时输出错误的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>