Linked Lists Help C++ - c++

I am having trouble in C++ putting and displaying array into a linked list. I'm having lots of trouble with linked lists in general
Here is my code. It only displays the first number. (It should display 19 21 17 22 33)
#include <iostream>
using namespace std;
struct node {
int age;
node *next;
};
void display(node *t)
{
node *temp = t;
cout << temp->age << " ";
}
int main()
{
int Age[5] = { 19, 21, 17, 22, 33 };
node* List = new node;
List = NULL;
node* temp2 = List;
while (temp2 != NULL)
{
temp2 = temp2->next;
node* List = new node;
List = NULL;
node* temp2 = List;
}
for (int i = 0; i < 5; i++)
{
temp2 = new node;
temp2 -> age = Age[i];
temp2 -> next = NULL;
if (List == NULL)
List = temp2;
}
display(List);
system("PAUSE");
return 0;
}

Take the following code as an example. Note that you have to delete all created nodes at the end of program to avoid memory leaks.
#include <iostream>
#include <cstddef>
using namespace std;
struct node {
int age;
node* next;
};
void display(node* list) {
while (list != NULL) {
cout << list->age << ' ';
list = list->next;
}
}
node* create(int age) {
node* t = new node;
t->age = age;
t->next = NULL;
return t;
}
void add(node* list, node* t) {
while (list->next != NULL) {
list = list->next;
}
list->next = t;
}
void release(node* list) {
while (list != NULL) {
node* t = list;
list = list->next;
delete t;
}
}
int main() {
int arr[5] = { 19, 21, 17, 22, 33 };
node* list = create(arr[0]);
for (int i = 1; i < 5; i++) {
node* t = create(arr[i]);
add(list, t);
}
display(list);
release(list);
system("PAUSE");
return 0;
}

There's a lot going on here. I'd recommend you look through some tutorials to help solidify your understanding of pointers and linked lists.
To answer your question, let's step through what's happening:
In your main function, you dynamically allocate a node object and have List point to this object. Then, you set List to NULL. When you initialize the node pointer temp2 to List, temp2 also points to NULL.
Because temp2 = NULL, you skip over the following while loop.
In the first iteration of your for loop, you re-assign temp2 to a newly created object, then set the age for that node to the Age[0]. When we get to your if statement, List = NULL so we enter the conditional statement and set List to temp2 where temp2->age = Age[0].
For each additional iteration of your for loop, List no longer is equal to NULL so you never enter your if statement again. List still points to the node where age = Age[0].
When you get to your display function, assuming it was written to loop through a linked list, your List pointer is a list with one node where age = 19. Assuming your had a linked list with multiple valid nodes, your display() function doesn't iterate over them.

Related

created a linked list to insert an array in it, but it's not giving desired output

I had created a program to create a linked list and insert an array in it. But it's not giving the desired output, may be the problem is in display function
#include <iostream>
using namespace std;
//node
class node {
public:
int data;
node *next;
} *head = nullptr;
//function to insert array in linkedlist
void create(int A[], int n) {
node *head = new node;
node *temp;
node *last;
head->data = A[0];
head->next = nullptr;
last = head;
for (int i = 1; i < n; i++) {
//temp is an temporary variable which creates each time and last remebers its position
temp = new node;
temp->data = A[i];
cout << temp->data << endl;
temp->next = nullptr;
last->next = temp;
last = temp;
}
}
//function to display linked list which can access head because it is global
void display() {
node *p = head;
while (p != nullptr) {
cout << p->data << endl;
p = p->next;
}
}
int main() {
int A[] = {1, 6, 9, 4, 5, 6};
node *head;
create(A, 6);
display();
return 0;
}
Maybe I understand something wrong like to add display function in class. But I had never seen a class pointer having functions.
This is my first linked list program. If you could share some good info about it please do, thank you
The problem is that you have multiple variables named head being used for different purposes. You have a global variable head, which your display() function uses, but your create() function does not populate. create() populates a local variable named head instead, which shadows the global variable. display() never sees the created list. And main() has its own local variable named head, which is not being used for anything at all.
Get rid of the global variable. Make create() return the list it creates. And then make main() pass that list to display().
Try something like this:
#include <iostream>
using namespace std;
//node
class node {
public:
int data;
node *next;
};
//function to insert array in linkedlist
node* create(int A[], int n) {
node *head = nullptr;
node **p = &head;
for (int i = 0; i < n; i++) {
*p = new node{ A[i], nullptr };
p = &((*p)->next);
}
return head;
}
//function to display linked list
void display(const node *head) {
node *p = head;
while (p != nullptr) {
cout << p->data << endl;
p = p->next;
}
}
//function to destroy linked list
void destroy(node *head) {
node *p = head;
while (p != nullptr) {
node *next = p->next;
delete p;
p = next;
}
}
int main() {
int A[] = {1, 6, 9, 4, 5, 6};
node *head = create(A, 6);
display(head);
destroy(head);
return 0;
}

Trying to initialize a linked list using array

I need to define a class of linked list,List, in a way such that object of class can be defined in two ways,
List obj1 = L1();//head=0
List obj2 = L2(given_arr[], size of array) // I would be given an array, whose elements are elements of list
so, I need to form a construter for both,
for obj1, Its easy.
List(){head=0};
But I am not abe to do so for second type of object.
I tried to form a program for this.
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head;
int arr[];
List() { head = 0; }
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
int i;
head->val = arr[0];
for (i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[4] = {9, 89, 0, 43};
List* M = new List();
List* L = new List(barr[4], 4);
L->display();
return 0;
}
This program doesn't work. Please suggest a way to do so.
Make these changes to your main().
int main() {
int barr[] = {9, 89, 0, 43}; // No need to specify size if you're initializing
// List* M = new List(); // unused
// Your array is barr, barr[4] makes no sense. You also don't allocate the List,
// the list allocates
List L = List(barr, sizeof(barr) / sizeof(barr[0]);
L.display(); // -> to .
return 0;
}
This now compiles, but immediately segfaults. Simply running the program in the debugger shows a simple error. The line head->val = arr[0]; attempts to dereference a null pointer. Which takes us to the next thing. Use nullptr, not NULL or 0.
Your array constructor was over-complicated, you just need this:
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
Your addnode() function already handled an empty list. Fixing that, your code should run. I made a couple other small changes, mostly trimming cruft out. Here's your complete code:
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head = nullptr;
List() = default;
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[] = {9, 89, 0, 43};
List L = List(barr, sizeof(barr) / sizeof(barr[0]));
L.display();
return 0;
}

Reverse linked list using double pointer

How to reverse linked list using double pointer?
I was learning about double pointers and thought if we can reverse linked list using one pointer only.
Conversion to using a pointer to pointer left as an exercise for the reader. Also has some distinct shortcomings in terms of style.
#include <iostream>
struct node {
int data;
node *next;
};
node *reverse(node *list) {
node *prev = NULL;
node *next;
while (list) {
next = list->next;
list->next = prev;
prev = list;
list = next;
}
return prev;
}
void show_list(node *list) {
while (list != NULL) {
std::cout << list->data << ", ";
list = list->next;
}
}
int main() {
node *list = NULL;
for (int i=0; i<10; i++) {
node *n = new node;
n->next = list;
n->data = i;
list = n;
}
std::cout << "As built: ";
show_list(list);
list = reverse(list);
std::cout << "Reversed: ";
show_list(list);
return 0;
}
If you decide to modify a pointer you received as a parameter, it's probably easier to deal with a reference to a pointer than a pointer to a pointer though.

Error "Abort signal from abort(3) (sigabrt) " for linked list in C++

The following code is for a basic circular linked list, but when one inputs a large value for n(e.g 8 digits) it throws the "abort signal from abort(3) (sigabrt)" error. I'm not sure what it means and would love some guidance about fixing this with regard to my code.
Thank you!
#include<bits/stdc++.h>
using namespace std;
//First I created a structure for a node in a circular linked list
struct Node
{
int data;
struct Node *next;
};
// function to create a new node
Node *newNode(int data)
{
Node *temporary = new Node;
temporary->next = temporary;
temporary->data = data;
return temporary;
}
// This function finds the last man standing in
//the game of elimination
void gameOfElimination(int m, int n)
{
//first I created a circular linked list of the size which the user inputted
Node *head = newNode(1);
Node *prev = head;
//this loop links the previous node to the next node, and so on.
for (int index = 2; index <= n; index++)
{
prev->next = newNode(index);
prev = prev->next;
}
prev->next = head; //This connects the last and first nodes in our linked list together.
//when only one node is left, which is our answer:
Node *ptr1 = head, *ptr2 = head;
while (ptr1->next != ptr1)
{
int count = 1;
while (count != m)
{
ptr2 = ptr1;
ptr1 = ptr1->next;
count++;
}
/* Remove the m-th node */
ptr2->next = ptr1->next;
ptr1 = ptr2->next;
}
printf ("%d\n ",
ptr1->data);
}
//main program which takes in values and calls the function:
int main()
{
int n, p;
cin>>n>>p;
int m=p+1;
gameOfElimination(m, n);
return 0;
}
SIGABRT is generally issued when there are memory issues (heap corruption being quite common). In your code, I see only the new() operator being called, but you aren't deleting any unused nodes from your linked list! Seems like you're exhausting the memory allocated to your process.
You might be running out of memory. Check your ram usage during the execution of your program, that might lead to something.
enter code here
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void traverse(Node *head)
{
while (head != NULL)
{
/* code */
cout<<head->data<<"->";
head = head->next;
}
cout<<"NULL"
}
int main()
{
Node *head = new Node();
Node *second = new Node();;
Node *third = new Node();;
Node *fourth = new Node();;
head->data = 5;
head->next = second;
//cout<<head->data;
second->data=10;
second->next=third;
third->data = 15;
third->next = fourth;
fourth->data = 20;
fourth->next= NULL;
traverse(head);
return 0;
}```

Circular linked list: Infinite loop

I'm trying to make a circular link list but i'm facing with a problem.
If i run the program with those 2 lines of code above, when i compile and run, it gets an infinite loop of cin if the number of elements is higher than 2. Without them works fine but it isn't anymore a circular linked list. Can you help ?
The problem is right here:
toPush->next = head;
head->pred = toPush;
Full code:
#include <iostream>
using namespace std;
typedef int data;
// Nodes
struct elements {
data value;
elements* next;
elements* pred;
};
// Function that pushes the element to the end
void insertElementEnding(elements* &head, data var) {
elements* toPush = new elements;
toPush->value = var;
toPush->next = NULL;
toPush->pred = NULL;
if(head == NULL) {
head = toPush;
} else {
elements* node = new elements;
node = head;
while(node->next != NULL) {
node = node->next;
}
node->next = toPush;
toPush->pred = node;
toPush->next = head;
head->pred = toPush;
}
}
// Function that prints the list
void showList(elements* head, int numbers) {
for(int i = 0; i < numbers && head != NULL; i++) {
cout << head->value;
head = head->next;
}
}
int main() {
elements* head = NULL;
int var, n;
cout << "Introduce the number of elements: ";
cin >> n;
for(int i = 0; i < n; i++) {
cin >> var;
insertElementEnding(head, var);
}
showList(head, n);
return 0;
}
Thanks in advance.
You need to look for the start of the loop, not NULL, ie
while(node->next != NULL)
should be
while(node->next != head)
As a sidenote, you should use nullptr instead of NULL in C++.
Also you have a memory leak in your program. You dont need to allocate new memory just to get a pointer for iterating your list. This right here is the problem:
elements* node = new elements;
node = head;
A better way would just be
elements* node = head;
First, validation for NULL makes sense only to check if the list is not initialized, before inserting the first element in it.
For all other cases it is redundant as the head should always have previous and following elements for the circle. In case it is just one in the least, it points to itself.
Then if you change the function slightly, it will resolve the problem
void insertElementEnding(elements* &head, data var) {
elements* toPush = new elements;
toPush->value = var;
if(head == NULL) {
head = toPush;
head->next = toPush;
head->pred = toPush;
} else {
// insert the new element before the head
head->pred->next = toPush;
head->pred = toPush;
}
}