while即使我設定了陳述句,這些陳述句也會繼續運行!= 0。正常作業的displayLinkedList使用迭代,displayLinkedListRe作為無限回圈運行的使用遞回。此外,由于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);
}
uj5u.com熱心網友回復:
有多個問題:
回圈
createLinkedList運行一次太多:你應該寫對于 (i = 1; i < n; i )
功能
displayLinkedList()和sizeOfLinkedList()停止過早。你應該寫:
void displayLinkedList(struct node *p) {
while (p != NULL) {
cout << "the element is " << p->data << endl;
p = p->p;
}
}
displayLinkedListRe在無限回圈中遞回!要么使用回圈,要么使用遞回,但不能同時使用。malloc()此外,不建議在 C 中分配物件,尤其是不包括<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 ;
}
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438335.html
