inserting an element in a linked list - c

Considering a linked list containing five elements.
1,2,3,4,5 a no '7' is to be inserted after two. we will have an head pointing to the first element of the linked list and ptr at the last. while inserting an element before 3 we will loop through the linked list starting from head to last and we will introduce another pointer(prev) to hold the previous pointers address.ptr will point to the current node and if a matching data is found(3) then we have to include the new node between 2 and 3.
We can do it as we have previous pointer.How to do it without using a previous pointer.
EDITED:
#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list* link;
};
struct list *head=NULL;
struct list *tail=NULL;
void createList(int value);
void displayList(struct list* head_node);
void insertNewNode();
int value;
int main()
{
int i;
for(i=0;i<5;i++)
{
printf("\nEnter the data to be added into the list:\n");
scanf("%d",&value);
createList(value);
}
printf("\nCreated Linked list is\n");
//displayList(head);
printf("\nInsert a node\n");
insertNewNode();
displayList(head);
return 0;
}
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node,*prev=NULL;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr;ptr=ptr->link)
{
if(ptr->data == 3)
{
printf("Found");
new_node->data = val;
prev->link=new_node;
new_node->link = ptr;
}
prev = ptr;
}
}
void createList(int value)
{
struct list *newNode;
newNode = (struct list*)malloc(sizeof(struct list));
//tail = (struct list*)malloc(sizeof(struct list));
newNode->data = value;
if(head == NULL)
{
head = newNode;
}
else
{
tail->link = newNode;
}
tail = newNode;
tail->link = NULL;
}
void displayList(struct list *head_node)
{
struct list *i;
for(i=head;i;i=i->link)
{
printf("%d",i->data);
printf(" ");
}
printf("\n");
}

void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr;ptr=ptr->link)
{
if(ptr->data == 2)
{
printf("Found");
new_node->data = val;
new_node->link = ptr->link;
ptr->link = new_node;
}
}
}
Update:
This is probably what you want:
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr->link;ptr=ptr->link)
{
if(ptr->link->data == 3)
{
printf("Found");
new_node->data = val;
new_node->link = ptr->link;
ptr->link = new_node;
}
}
}
Here:
if(ptr->link->data == 3)
you simply look ahead to check if next node has value that you need.

Let's call curr the pointer at the current element, next the pointer at the next element, and value the number stored.
Traverse the list until curr.value == 2, now just create a new_node with new_node.value = 7 and set new_node.next = curr.next and curr.next = new_node

Related

Segmentation fault in linked list program (c language)

I'm trying to write a code for linked lists using c++. Insert at begin and Insert at end are not working for some reason. Here is the code.
`
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head;
int main()
{
struct Node *temp, *newnode;
int ch=1, i=1, info;
head = NULL;
while(ch)
{
printf("Enter data: ");
scanf("%d", &info);
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if(head == NULL)
{
head = newnode;
temp = newnode;
}
else
{
temp ->link = newnode;
temp = newnode;
}
printf("You wish to continue? (press 0 to terminate)\n");
scanf("%d",&ch);
if(!ch)
{
break;
}
}
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
//printLL();
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode->data = info;
printf("\n%d\n", newnode ->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *temp, *newnode;
newnode->link = NULL;
newnode->data = info;
temp = head;
while(temp!=NULL)
{
temp = temp->link;
}
temp->link = newnode;
printf("\n%d\n", newnode -> data);
}
void printLL()
{
struct Node *temp;
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
}
`
The problem is somewhere around newnode->data = info in the functions.
I created two functions, one to insert an element at beginning and one to insert an element at end. In both of them, i've created a newnode. The problem is I cannot insert data into those nodes.
When you want to append a new node to the end of a linked list, you must find your last node (a node which its link is NULL, not itself). Also, it is better to use meaningful variable name (temp is too general name). You also forgot to malloc new nodes in insertAtBeginning and insertAtEnd functions. I've fixed these issues in the following code
#include<stdio.h>
#include<stdlib.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
int main()
{
struct Node *it, *newnode, *tail;
int ch=1, i=1, info;
while(ch){
printf("Enter data: ");
scanf("%d", &info);
newnode = malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if (head == NULL) {
head = newnode;
tail = newnode;
} else {
tail->link = newnode;
tail = newnode;
}
printf("You wish to continue? (press 0 to terminate, else to continue)\n");
scanf("%d",&ch);
if(ch == 0) {
break;
}
}
it = head;
while(it != NULL) {
printf("%d -> ",it->data);
it = it->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode = malloc(sizeof(struct Node));
newnode->data = info;
printf("\n%d\n", newnode->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *it, *newnode;
newnode = malloc(sizeof(struct Node));
newnode->link = NULL;
newnode->data = info;
it = head;
while(it->link != NULL)
{
it = it->link;
}
it->link = newnode;
printf("\n%d\n", newnode->data);
}
void printLL()
{
struct Node *it;
it = head;
while(it!=NULL)
{
printf("%d -> ",it->data);
it = it->link;
}
}
You're treating your uninitialized stack variable (struct Node *newnode) as a pointer to a struct Node and trying to update its fields:
struct Node *newnode;
newnode->data = info;
This doesn't work because the value of newnode is whatever garbage was on the stack beforehand, and trying to deref it (*newnode) will likely give a seg fault since you're trying to read from some unknown memory address.
Notice how inside main, you assign a result from malloc to newnode, this means you know that (given that malloc didn't return NULL), the pointer is valid, and you're free to use the memory it points to.

Element deletion in single linked list at head not working

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
void insertAtBeg(struct node *n, int data) {
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = head;
head = temp;
}
void insertAtEnd(struct node *n, int data) {
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
}
void deleteElement(struct node *head, int data) {
if (head->data == data) {
struct node *temp;
temp = head;
head = head->next;
free(temp);
printf("after deletion at head in function\n");
printList(head);
}
}
void printList(struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
void main() {
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
insertAtBeg(head, 0);
printf("after insertion at beginning\n");
printList(head);
insertAtEnd(head, 4);
printf("after insertion at End\n");
printList(head);
deleteElement(head, 0);
printf("after deletion at head in main\n");
printList(head);
}
output of the code is
1
2
3
after insertion at beginning
0
1
2
3
after insertion at End
0
1
2
3
4
after deletion at head in function
1
2
3
4
after deletion at head in main
0
1
2
3
4
Why is there a difference in output of the function called in main and the function called in another function.ie.after deletion at head in function and after deletion at head in main, when both are supposed to be deleting element from the same list
The problem is you need a way to modify the head of the list when inserting and/or deleting elements from the list.
A simple way to do this is for these functions to return a potentially updated value of the head pointer and for the caller to store this return value into it's head variable.
Here is a modified version of your code with these semantics:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *insertAtBeg(struct node *head, int data) {
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
// should test for memory allocation failure
temp->data = data;
temp->next = head;
return temp;
}
struct node *insertAtEnd(struct node *head, int data) {
struct node *temp;
struct node *n;
temp = (struct node*)malloc(sizeof(struct node));
// should test for memory allocation failure
temp->data = data;
temp->next = NULL;
if (head == NULL)
return temp;
n = head;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
return head;
}
struct node *deleteElement(struct node *head, int data) {
// delete the first node with a given data
if (head->data == data) {
struct node *temp = head;
head = head->next;
free(temp);
} else {
struct node *n = head;
while (n->next != NULL) {
if (n->next->data == data) {
struct node *temp = n->next;
n->next = temp->next;
free(temp);
break;
}
}
}
return head;
}
void printList(const struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
int main() {
struct node *head = NULL;
head = insertAtBeg(head, 1);
head = insertAtEnd(head, 2);
head = insertAtEnd(head, 3);
printList(head);
head = insertAtBeg(head, 0);
printf("after insertion at beginning\n");
printList(head);
head = insertAtEnd(head, 4);
printf("after insertion at End\n");
printList(head);
head = deleteElement(head, 0);
printf("after deletion at head in main\n");
printList(head);
// should free the list
return 0;
}
An alternative is to pass the address of the list head pointer so the function can modify it if needed.
Here is a modified version of your code with this alternative approach:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *insertAtBeg(struct node **headp, int data) {
struct node *temp = malloc(sizeof(*temp));
if (temp != NULL) {
temp->data = data;
temp->next = *headp;
*headp = temp;
}
return temp;
}
struct node *insertAtEnd(struct node **headp, int data) {
struct node *temp = malloc(sizeof(*temp));
if (temp != NULL) {
temp->data = data;
temp->next = NULL;
if (*headp == NULL) {
*headp = temp;
} else {
struct node *n = *headp;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
}
}
return temp;
}
int deleteElement(struct node **headp, int data) {
// delete the first node with a given data
struct node *head = *headp;
if (head->data == data) {
*headp = head->next;
free(temp);
return 1; // node was found and freed
} else {
struct node *n = head;
while (n->next != NULL) {
if (n->next->data == data) {
struct node *temp = n->next;
n->next = temp->next;
free(temp);
return 1; // node was found and freed
}
}
return 0; // node not found
}
}
void printList(const struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
int main() {
struct node *head = NULL;
insertAtBeg(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
printList(head);
insertAtBeg(&head, 0);
printf("after insertion at beginning\n");
printList(head);
insertAtEnd(&head, 4);
printf("after insertion at End\n");
printList(head);
deleteElement(&head, 0);
printf("after deletion at head in main\n");
printList(head);
// free the list
while (head != NULL) {
deleteElement(&head, head->data);
}
return 0;
}
This alternative approach uses double pointers, so it is a bit more difficult for beginners to comprehend, but it has a strong advantage: the functions can update the list pointer and provide a meaningful return value that can be tested to detect errors. For example insertAtBeg() and insertAtEnd() return NULL if the new node could not be allocated but preserve the list. Similarly deleteElement() can return an indicator showing whether the element was found or not.
With this approach, you can write functions to pop the first or last element of the list, or the one at a given index, or one with a given data, while updating the list pointer as needed.
In the function void deleteElement(struct node *head,int data) you are passing a pointer to the head node. If you make changes to the node, then that works because you are pointing to the actual node. However, the variable head is a local copy of the pointer, which is not the one in main. When you change head to head->next that is only changing the local copy, so it has no effect outside deleteElement.
ADVANCED LEVEL POINTERS
To actually change head you have to pass a pointer to it, making a double pointer:
void deleteElement(struct node **phead,int data) {
struct node *temp;
temp = *phead;
*phead = (*phead)->next;
this means you have to pass the address of head &head as the parameter.

Adding a node at the beginning of a Singly Linked List (C)

The code works without error but I cant seem to know why the new node is not being inserted to the beginning of the list. It probably has something to do with the else statement in the first function (insertNode) but I'm not sure, what's going on?
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
void insertNode(struct node *head, int x) {
//Create node to be added and add the input integer to it
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = x;
//Check if there are any existing nodes in the list, if not, the let the head be equal to the new temp pointer
if (head == NULL) {
head = temp;
} else {
//If not, then we need to add the node to the beginning
temp->link = head;
head = temp;
printf("Node was added successfully!\n");
}
}
int findsize(struct node *head) {
//Finds the size of the list
struct node *temp = head;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->link;
}
return count;
}
void printData(struct node *head) {
//Prints the elements of the list
struct node *temp = head;
while (temp != NULL) {
printf("Element: %d\n", temp->data);
temp = temp->link;
}
}
void main() {
//Created a node and allocated memory
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
//Added data to the node and created another one linked to it
head->data = 15;
head->link = (struct node *)malloc(sizeof(struct node));
head->link->data = 30;
head->link->link = NULL;
//Used the above function to add a new node at the beginning of the list
insertNode(head, 5);
//Print the size of the list
printf("The size of the list you gave is: %d\n", findsize(head));
//Print the elements of the list
printData(head);
}
When you insert a node at the beginning of the list, you effectively change the beginning of the list, so this new initial node must be returned to the caller. The prototype for insertNode() must be changed to return the list head or to take a pointer to the list head.
Here is a modified version with the first approach:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
struct node *insertNode(struct node *head, int x) {
//Create node to be added and add the input integer to it
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
if (temp != NULL) {
temp->data = x;
temp->link = head;
}
return temp;
}
int findsize(struct node *head) {
//Find the size of the list
struct node *temp = head;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->link;
}
return count;
}
void printData(struct node *head) {
//Prints the elements of the list
struct node *temp = head;
while (temp != NULL) {
printf("Element: %d\n", temp->data);
temp = temp->link;
}
}
void main() {
//Created a node and allocated memory
struct node *head = NULL;
//Insert 3 nodes with values 30, 15 and 5
head = insertNode(head, 30);
head = insertNode(head, 15);
head = insertNode(head, 5);
//Print the size of the list
printf("The size of the list you gave is: %d\n", findsize(head));
//Print the elements of the list
printData(head);
//Should free the nodes
return 0;
}

linked list using double pointers

Using double pointers first time to create and display linked list
#include "stdio.h"
#include "stdlib.h"
struct node
{
int data;
struct node * next;
};
void Insert(struct node **, int , int );
void display(struct node *);
int main()
{
int c, data, position;
struct node* head;
do{
printf("Enter a choice :\n");
printf("1. Add an element.\n");
printf("2. Del an element.\n3.Display List.\n");
printf("4.Delete linked list.\n5.Exit.\n");
printf("Your Choice :");
scanf("%d",&c);
switch(c){
case 1 :
printf("\nEnter data and position :\n");
scanf("%d %d",&data,&position);
Insert(&head,data,position);
break;
case 2 :
break;
case 3 :
printf("Linked List : \n");
display(head);
break;
case 4 :
break;
case 5 :
exit(0);
default :
printf("Invalid Choice.\n");
break;
}
}while(1);
return 0;
}
void Insert(struct node **ptrhead, int item, int position){
struct node *p,*newnode;
//node creation.
newnode = (struct node *)malloc(sizeof(struct node));
if (!newnode)
{
printf("Memory Error.\n");
return;
}
newnode->next = NULL;
newnode->data = item;
p = *ptrhead;
// Creates initial node
if (!(p->data))
{
p = newnode;
}
// insertion at beginning
if (position==1)
{
newnode->next = p;
p = newnode;
free(newnode);
}
// insertionn at middle or end.
else
{
int i=1;
while(p->next!=NULL && i<position-1){
p=p->next;
i++;
}
newnode->next = p->next;
p->next = newnode;
}
*ptrhead = p;
};
// Display Linked list
void display(struct node *head){
if (head)
{
do{
printf("%d\n", head->data);
head = head->next;
}while(head->next);
}
};
I will add functions for deletion and other operations later. Right now , I just want to insert and display fns to work . But output comes as infinitely running loop with wrong values. I cannot figure out what's wrong in my code , please help ?
Thanks in advance.
Not sure why somebody would be writing this type of C today, looks like maybe I'm doing your homework for you... In any case, you asked to fix your code, not rewrite it, so here's the minimum set of changes.
head should be initialized to NULL.
if (!(p->data)) is not right. That if statement should just be:
// Creates initial node
if (!p)
{
*ptrhead = newnode;
return;
}
Remove free(newnode);.
The insert at middle/end code could be
int i = 1;
struct node *n = p;
while (n->next != NULL && i<position - 1){
n = n->next;
i++;
}
newnode->next = n->next;
n->next = newnode;
The final insert function:
void Insert(struct node **ptrhead, int item, int position)
{
struct node *p, *newnode;
//node creation.
newnode = (struct node *)malloc(sizeof(struct node));
if (!newnode)
{
printf("Memory Error.\n");
return;
}
newnode->next = NULL;
newnode->data = item;
p = *ptrhead;
// Creates initial node
if (!p)
{
*ptrhead = newnode;
return;
}
// insertion at beginning
if (position == 1)
{
newnode->next = p;
p = newnode;
}
// insertionn at middle or end.
else
{
int i = 1;
struct node *n = p;
while (n->next != NULL && i<position - 1){
n = n->next;
i++;
}
newnode->next = n->next;
n->next = newnode;
}
*ptrhead = p;
}
Your print function isn't quite right, just make it:
// Display Linked list
void display(struct node *head)
{
while (head)
{
printf("%d\n", head->data);
head = head->next;
}
}

LinkedList functions crash in c

I implemented a linked list in c. when i test it, whenever i reach display function or insert at the end the program crashes. These are the functions:
struct Node
{
char data;
struct Node *next;
};
struct LinkedList
{
struct Node *head;
};
void insertAtBeginning(struct LinkedList *LL, char ele)
{
struct Node *new = (struct Node*)malloc(sizeof(struct Node));
new->data = ele;
new->next = NULL;
if(new->data == '\n')return;
if(LL->head==NULL)LL->head = new;
else
{
new->next=LL->head;
LL->head=new;
}
}
void insertAtTheEnd(struct LinkedList *LL, char ele)
{
struct Node *new = (struct Node*) malloc(sizeof(struct Node));
new->data = ele;
new->next = NULL;
if(LL->head==NULL){LL->head=new;return;}
struct Node *current = LL->head;
while(current->next != NULL) {current = current->next;}
current->next = new;
}
void deleteNode(struct LinkedList* LL, char ele)
{
struct Node *current = LL->head;
struct Node *temp = LL->head;
while(current->next->data!=ele && current!=NULL)current=current->next;
temp=current->next;
current->next=current->next->next;
free(temp);
}
void deleteFirstNode(struct LinkedList* LL)
{
struct Node *temp;
if(LL->head != NULL)
{
temp = LL->head;
LL->head = LL->head->next;
free(temp);
}
}
void displayLinkedList(struct LinkedList LL)
{
struct Node *current = LL.head;
printf("List: ");
while(current != NULL)
{
printf("%c",current->data);
current = current->next;
}
printf("\n");
}
This is the main:
main()
{
struct LinkedList LL;
char c = '0';
//Inserting at beginning
printf("Type a string. Press Enter to end: ");
while(c != '\n')
{
scanf("%c",&c);
insertAtBeginning(&LL, c);
}
printf("List: ");
displayLinkedList(LL);
printf("\n");
//Inserting at end
c='0';
printf("Type a string. Press Enter to end: ");
while(c != '\n')
{
scanf("%c",&c);
insertAtTheEnd(&LL, c);
}
printf("List: ");
displayLinkedList(LL);
printf("\n");
//Remove
printf("Enter a char to remove: ");
scanf("%c",&c);
deleteNode(&LL, c);
printf("\n");
printf("List: ");
displayLinkedList(LL);
printf("\n");
deleteFirstNode(&LL);
printf("List: ");
displayLinkedList(LL);
}
of course This is done after inserting the necessary libraries.
you have to set NULL to next when you create element. if you do not do it, your while loop behaviour will be buggy
void insertAtTheEnd(struct LinkedList *LL, char ele)
{
struct Node *new = (struct Node*) malloc(sizeof(struct Node));
new->next = NULL;
new->data = ele;
if(LL->head == NULL) LL->head = new;
else
{
struct Node *current = LL->head;
while(current->next != NULL) {current = current->next;}
current->next = new;
}
}
, and do same for other functions.
also you have to set NULL to your LinkedList.head. so, set NULL when you define LinkedList
struct LinkedList LL;
LL.head = NULL;
i asume the line if(current = LL->head) is wrong
bacause temp = current->next would crash if the result is NULL
otherwise the code after the if statement doesnt makes sense
There are some instances where you will try to insert at the end. When you have something of the form node_new->next->prev = node, you must check to make sure that node_new->next is not NULL, because NULL does not have any type and thus does not have a prev field.
You may also consider making all of your functions return int, so that you can know if and what goes wrong.

Resources