I am trying to display the second list. when I run the code, the second list gets printed but the compiler throws an exception that says "cur was 0xCDCDCDCD".
I am trying to let the user input a list and then the compiler creates a second list with the square of elements of the first list.
here's the code with the question.
/*
Write a program that inputs from the user a simple linked list of integer elements. The
program should create a new list that is the list of the square of the elements of the
previous list. Output the list.
*/
#include <iostream>
#include <cmath>
using namespace std;
struct node {
int data;
node* next;
};
node* input(int n) {
node* cur, * head, * tmp;
tmp = new node;
cout << "enter a new node" << endl;
cin >> tmp->data;
head = tmp;
cur = tmp;
for (int i = 0; i < n - 1;i++) {
tmp = new node;
cout << "enter a new node" << endl;
cin >> tmp->data;
cur->next = tmp;
cur = tmp;
}
return head;
}
node* square(node* head, int n) {
node* head1, * cur, * cur1, * tmp;
cur= head;
tmp = new node;
tmp->data = pow(cur->data, 2);
head1 = tmp;
cur1 = tmp;
cur = cur->next;
for (int i = 0;i < n - 1;i++) {
tmp = new node;
tmp->data = pow(cur->data, 2);
cur1->next = tmp;
cur1 = tmp;
cur = cur->next;
}
return head1;
}
void displayList2(node* head1) {
node* cur;
cur = head1;
while (cur != NULL) {
cout << cur->data << " ";
cur = cur->next;
}
}
int main() {
int n;
cout << "enter number of nodes: ";
cin >> n;
node* head, * head1;
head = input(n);
head1 = square(head, n);
displayList2(head1);
}
is there a problem with the heap memory or something similar? what am I doing wrong?