链表上的无限循环

infinite loop on linked list

即使我设置语句 != 0while 语句仍保留在 运行 上。 displayLinkedList 使用正常工作的迭代, displayLinkedListRe 使用递归,即 运行 作为无限循环。此外,由于某种原因,应该 return 链表的函数 sizeOfLinkedList 也是 运行 作为无限循环。

#include <iostream>

using namespace std;

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

void createLinkedList(int a[], int n) {
    int i;
    struct node *last, *t;
    first = (struct node *)malloc(sizeof(struct node));
    first->data = a[0];
    first->p = NULL;
    cout << first->p << endl;
    last = first;

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

void displayLinkedList(struct node *p) {
    while (p->p != 0) {
        cout << "the element is " << p->data << endl;
        p = p->p;
    }
}

int sizeOfLinkedList(struct node *pointer) {
    int n{ 0 };
    while (pointer->p != NULL) {
        n++;
    }
    return n;
}

int displayLinkedListRe(struct node *pointer) {
    while (pointer->p != NULL) {
        cout << pointer->data << endl;
        displayLinkedListRe(pointer->p);
    }
    return 0;
}

int main() {
    int array[] = { 1, 2, 3, 4, 5, 6, 7 };
    createLinkedList(array, 7);
    displayLinkedList(first);
    displayLinkedListRe(first);
    cout << "the size of linked list is " << sizeOfLinkedList(first);
}

存在多个问题:

  • createLinkedList中的循环运行了一次太多:你应该写

    for (i = 1; i < n; i++)
    
  • 功能 displayLinkedList() 停止得太快了。你应该写:

    void displayLinkedList(struct node *p) {
        while (p != NULL) {
            cout << "the element is " << p->data << endl;
            p = p->p;
        }
    }
    
  • 在函数sizeOfLinkedList()中,你没有在循环体内更新p,所以循环一直运行。

  • displayLinkedListRe 在循环内递归,你也不更新 p !使用循环或递归,但不能同时使用。

  • 此外,不推荐在 C++ 中使用 malloc() 分配对象,尤其是不包括 <stdlib.h>.

这是修改后的版本:

#include <iostream>

using namespace std;

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

void createLinkedList(const int a[], int n) {
    if (n <= 0)
        return;

    node *first = new node;
    first->data = a[0];
    first->p = NULL;
    node *last = first;

    for (int i = 1; i < n; i++) {
        node *t = new node;
        t->data = a[i];
        t->p = NULL;
        last->p = t;
        last = t;
    }
}

void displayLinkedList(const struct node *p) {
    while (p != NULL) {
        cout << "the element is " << p->data << endl;
        p = p->p;
    }
}

int sizeOfLinkedList(const struct node *p) {
    int n = 0;
    while (p != NULL) {
        n++;
        p = p->p;
    }
    return n;
}

void displayLinkedListRe(const struct node *p) {
    if (p != NULL) {
        cout << p->data << endl;
        displayLinkedListRe(p->p);
    }
}

int main() {
    int array[] = { 1, 2, 3, 4, 5, 6, 7 };
    createLinkedList(array, 7);
    displayLinkedList(first);
    displayLinkedListRe(first);
    cout << "the size of linked list is " << sizeOfLinkedList(first);
}