Creating Linked List using For Loop (c++) - c++

I was trying to create a linked list using a for loop but the 'new' in the for loop in the create() method didn't quite allocate a new slot to store new data. As a result, when I tried to print the list, I got an infinite loop. Can somebody tell me what's wrong here?
struct node
{
double value;
node * next_ptr;
node(){}
node(double val, node * p): value(val), next_ptr(p) {}
~node(){}
};
node * create()
{
using namespace std;
node temp = {0, nullptr};
node * result;
for(int i=1; i<5; ++i)
{
result = new node;
result->value = i;
result->next_ptr = &temp;
temp = *result;
}
return result;
};

The reason you are probably getting an infinite loop is because in:
temp = *result;
you are copying the value of *result into a new object of type node, which is unrelated to the one you created.
What you want to do is store a pointer instead:
node* temp = nullptr;
node* result;
for(int i=0; i<5; ++i)
{
result = new node;
result->value = i;
result->next_ptr = temp;
temp = result;
}
return result;
Live demo
A part from the learning value, just stick to std::forward_list or std::list, for lists, instead. Or even better just use std::vector or other containers (depending on the use that you make of the container).

a simple one to create linked in for loop
#include <iostream>
class LinkedList {
public:
int value;
LinkedList * next;
};
int main()
{
LinkedList *List = nullptr;
LinkedList *head = List;
LinkedList *prev;
for (int i=0; i< 3;i++)
{
LinkedList *temp = new(LinkedList);
temp->value = i;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
prev = head;
}
else
{
prev->next = temp;
prev = temp;
}
}
}

Related

create linked list with for loop...why we should use l->next.....why we can just use l=t only to assigne the previous address of the node?

#include<iostream>
using std::cout;
struct node
{
int data;
node* next;
};
void Display(node* p)
{
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
node* t = new node{ 0 }, * head = t;
node* l = t;
for (size_t i = 1; i <= 5; i++)
{
t = new node;
t->data = i;
t->next = NULL;
l->next = t;
l = t;
}
Display(head);
return 0;
}
why we should use l->next=t ......is this a right way to fill a linked list throw a for loop or even copy items from an array or any source of data;
If you will write
l = t;
instead of
l->next = t;
l = t;
then the list will be broken because the data member next of the node pointed to by the pointer l will not point to the new node pointed to by the pointer t and will have the value NULL.
As a result you will have six separate nodes the data member next of which will be equal to NULL. So you will not have a linked list.

Why does my code stop running when it comes to pointers?

I need to make a simple program with linked lists but my code just stops running.
Down below are to codes, first is the main .cpp file, and the second is header where the problematic function is defined. The code stops when it comes to assigning "new_" pointer attributes (marked with arrows). The function, as its name says, need to generate a linked list from an array, and return the head of that list.
I am using dev c++ for compiling, and he is not throwing any error or warning.
<main.cpp>
#include<stdio.h>
#include"LinkedList2.h"
int main(){
node *head;
int A[] = {2,8,12,9,7};
int n = sizeof(A) / sizeof(A[0]);
head = CreateListFromArray(A, n);
PrintList(head);
return 0;
}
<LinkedList2.h>
#include<stdio.h>
typedef struct node_{
int x;
struct node_ *next;
}node;
node* CreateListFromArray(int A[], int n){
node *head = NULL, *tmp = head, *new_;
for(int i = 0; i < n; i++){
new_->next = NULL; // <------
new_->x = A[I]; // <------
tmp->next = new_;
tmp = tmp->next;
}
return head;
}
void PrintList(node *head){
for(node *tmp = head; tmp != NULL; tmp = tmp->next) printf("%d ", tmp->x);
}
you need to allocate memory for each new node
node* CreateListFromArray(int A[], int n){
node *head = NULL, *tmp = head;
for(int i = 0; i < n; i++){
node *new_ = new node():
new_->next = NULL; // <------
new_->x = A[I]; // <------
tmp->next = new_;
tmp = tmp->next;
}
return head;
}
you also dont have a valid head pointer either, i leave that for you to sort out
note in c++ you dont need typedef any more.
you also have to change A[I] to A[i], because I doesn't exist

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;
}
}

inserting element at the end of linked list

I am trying to insert element at the end of linked list but the while loop doesn't terminate. I am not able to understand why is this happening. Here is my code.
I am calling this function inside my main() function.
struct node{
int data;
struct node* link;
};
struct node * head;
void insert_last(int element){
struct node * temp = (node*)malloc(sizeof(struct node));
temp->data = element;
temp->link = NULL;
if(head==NULL){
head = temp;
}
struct node * temp1 = head;
while(temp1->link!=NULL){
temp1 = temp1->link;
}
temp1->link = temp;
}
Here is the main method:
int main()
{
head = NULL;
printf("Enter the no. of nodes or elements you want to make linked list of. ");
int n;
scanf("%d",&n);
int element = 0;
for(int i = 0; i<n; i++){
printf("Enter the element\n");
scanf("%d",&element);
insert_last(element);
std::cout<<"Element inserted\n\n";
}
//print_recursive(head);
print();
}
That's easy.
if(head==NULL){
head = temp;
}
In that case, you are already done with what are you doing. If you continue, temp1 becomes the temp. Then temp1->link = temp; makes this node point to itself. Second insertion will never find end because your list is circular now and while(temp1->link!=NULL) will never end.
What you should do is simply put return;.
if(head==NULL){
head = temp;
return;
}

Segmentation fault when creating linked list with function

I am trying to create a linked list and then echo the node values to the console. But using a function outside the main function and calling it is causing segmentation fault(core dumped). I can't figure it out why.
The following code works :
#include<iostream>
using std::cout;
using std::endl;
struct node
{
int val;
node* next;
};
void printList(node* start)
{
node* temp;
temp = start;
int i = 0;
while(temp->next != NULL)
{
cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
temp = temp->next;
i++;
}
}
int main()
{
node* start;
node* temp;
start = new node;
temp = start;
for(int i = 0; i < 10; i++)
{
temp->val = i*10;
temp->next = new node;
temp = temp->next;
}
temp->val = 0;
temp->next = NULL;
printList(start);
return 0;
}
But this throws a segmentation fault
#include<iostream>
using std::cout;
using std::endl;
struct node
{
int val;
node* next;
};
void createList(node* start)
{
node* temp;
start = new node;
temp = start;
for(int i = 0; i < 10; i++)
{
temp->val = i*10;
temp->next = new node;
temp = temp->next;
}
temp->val = 0;
temp->next = NULL;
}
void printList(node* start)
{
node* temp;
temp = start;
int i = 0;
while(temp->next != NULL)
{
cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
temp = temp->next;
i++;
}
}
int main()
{
node* start;
createList(start);
printList(start);
return 0;
}
Change void createList(node* start) to void createList(node*& start). (See it work).
In C++, unless specified otherwise, everything is passed by value. In this case, you're passing a pointer to a node (start) to createList by value. You can alter the node it points to (start->...), but not the pointer itself, as you're working with a copy.
Passing the pointer by reference allows you to change the pointer itself.
You're passing the start parameter into the function createList by value, which means that when you do
start = new node;
the copy of start is being assigned the address of the new node. This means that the start variable that you declare in main does not receive the address of the node.
To fix this, use a pointer reference. Pass start to createList by reference, instead of by value. Like this:
void createList(node*& start)
When you pass-by-reference, you're changing the pointer you declared in main directly, rather than creating a copy.