inserting element at the end of linked list - c++

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

Related

Deleting a node at nth position in a linked list in C++ ------ Last number is not getting deleted

On running this code, when I enter n as 4, the program stops instead of getting output as 2 4 6
I cant delete the last node in this linked list.
it works fine for all other position but not for the last node. Is it because the there is no (n+1)th node after the last node to which the (n-1)th node should point. and should I add some more code in the delete function explicitly to delete the last node?
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int data, int n)
{
struct Node* temp1 = new Node();
temp1->data = data;
temp1->next = NULL;
if(n == 1)
{
temp1->next = head;
head = temp1;
return;
}
struct Node* temp2 = head;
for(int i = 0; i<n-2; i++)
{
temp2 = temp2->next;
}
temp1->next =temp2->next;
temp2->next = temp1;
}
void Print()
{
struct Node* temp = head;
while(temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
printf("\n");
}
void Delete(int n)
{
struct Node* temp1 = head;
if(n == 1)
{
head = temp1->next;
free(temp1);
return;
}
int i;
for(i = 0; i<n-2; i++)
{
temp1 = temp1->next;
struct Node* temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
}
int main()
{
head = NULL;
Insert(2, 1);
Insert(4,2);
Insert(6,3);
Insert(5,4);
Print();
int n;
printf("Enter a position\n");
scanf("%d", &n);
printf("\n");
Delete(n);
Print();
}
Looks like you need to do a little more work on your delete algorithm. If you expand your test case to more than 4 nodes, I think you'll discover that there are more issues than just deleting the last node. I rewrote your delete function while trying to keep some of your same logic.
The comments mention some of your issues, but it looks like your for-loop calls free n-2 times. That's not what we want. We use the loop to "find" the node we want to delete, and then call free once (after reassigning the proper pointers)
void Delete(int n){
struct Node* temp1 = head;
if(n == 1)
{
head = temp1->next;
free(temp1);
return;
}
// Find the node right before the one you want to delete.
for(int i = 0; i<n-2; i++){
temp1 = temp1->next;
}
struct Node* node_to_be_deleted = temp1->next;
temp1->next = node_to_be_deleted->next;
free(node_to_be_deleted);
}
note: There's no error checking here...

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

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

Declaration of Head/First node in a Linked list

Hi all I'm having an issues in a linked list problem. Given two piece of code I've to find why one of them is not working
Code 1 is
struct node {
int data;
struct node *link;
};
void insert(struct node *head) {
struct node *last, *temp;
head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &head->data);
head->link = NULL;
last = head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}
void display(struct node *p) {
while(p) {
printf("%d ",p->data);
p = p->link;
}
return;
}
int main() {
struct node *head;
insert(head);
display(head);
return 0;
}
and second code is
struct node {
int data;
struct node *link;
}*head;
void insert() {
struct node *last, *temp;
head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &head->data);
head->link = NULL;
last = head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}
void display(struct node *p) {
while(p) {
printf("%d ",p->data);
p = p->link;
}
return;
}
int main() {
insert();
display(head);
return 0;
}
Now my question is why declaring head in main in the first is not giving o/p for display function wheres declaring it globally in second code is working? Asking this as I'm wondering that in first case head is declared in main and passed as an address so after coming back from insert function it should get the effect of that insert function operation but it's not working like the way and not giving ant o/p for display function
The issue is that, in the first code, insert receives a copy of the main's head pointer and modifies that copy by making it point to some newly allocated memory. That modification never propagates back to main.
To make it propagate, use a pointer to pointer:
void insert(struct node **head) {
struct node *last, *temp;
*head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &(*head)->data);
(*head)->link = NULL;
last = *head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}
and then, in main, call it like so:
insert(&head);
Alternatively, you could make insert take a pointer but also return a pointer (i.e. the new head):
struct node* insert(struct node *head) { ... }
One issue what that API is that it's rather error-prone: it's very easy to call insert() and forget to deal with its return value.

Why is it printing the last element in circular linked list?

In the below code, the number stored inside the last element is only being displayed, not the rest of elements.
#include <stdio.h>
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
struct node * Start = NULL;
struct node * End = NULL;
void CreateList(int num)
{
struct node *temp = new struct node;
int data,i=0;
while(true)
{
cout<<"Enter data \n";
cin>>data;
temp->data = data;
temp->next = Start;
if(Start==NULL)
{
Start = End = temp;
}
else{
End->next = temp;
End = temp;
}
if(i==num-1)
break;
i++;
}
}
void Display()
{
struct node* temp1;
temp1 = Start;
do{
cout<<temp1->data<<endl;
temp1=temp1->next;
} while(temp1!=Start);
}
int main()
{
int num;
cout<<"How many elements you want to input?\n";
cin>>num;
CreateList(num);
Display();
return 0;
}
I have done it using structure not classes. I have used two non-dynamic pointers 'Start' and 'End'. The main problem is coming in Display() function. The Display() is printing the value of the last element.
Output:
(Click image to enlarge)
You are not creating the required number of nodes in CreateList. You are creating a node using
struct node *temp = new struct node;
and are reusing the same node in the loop.
Here's an updated version of the function.
void CreateList(int num)
{
int data,i=0;
while(true)
{
cout<<"Enter data \n";
cin>>data;
// Create a new node for every data
struct node *temp = new struct node;
temp->data = data;
temp->next = Start;
if(Start==NULL)
{
Start = End = temp;
}
else{
End->next = temp;
End = temp;
}
if(i==num-1)
break;
i++;
}
}
Suggestion for futher cleanup. In C++, you don't need to use struct node. Just node is sufficient.
node* Start = NULL;
node* End = NULL;
and
// Create a new node for every data
node *temp = new node;