The while
statements are kept on running even when I set the statement != 0
.
The displayLinkedList
uses iteration which works normally,
the displayLinkedListRe
uses recursion, which is running as an infinite loop. Also, the function sizeOfLinkedList
which is supposed to return a linked list is also running as an infinite loop for some reason.
#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);
}
CodePudding user response:
There are multiple problems:
The loop in
createLinkedList
runs one time too much: you should writefor (i = 1; i < n; i )
The functions
displayLinkedList()
stops too soon. You should write:void displayLinkedList(struct node *p) { while (p != NULL) { cout << "the element is " << p->data << endl; p = p->p; } }
in function
sizeOfLinkedList()
, you do not updatep
in the loop body, so the loop runs forever.displayLinkedListRe
recurses inside the loop and you do not updatep
either! either use a loop or recursion but not both.Furthermore, allocating objects with
malloc()
in C is not recommended, especially without including<stdlib.h>
.
Here is a modified version:
#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);
}