Skip to content

Instantly share code, notes, and snippets.

@sr6033
Last active August 15, 2018 15:57
Show Gist options
  • Select an option

  • Save sr6033/ea722ffbd63fc3505642fb62f38109cb to your computer and use it in GitHub Desktop.

Select an option

Save sr6033/ea722ffbd63fc3505642fb62f38109cb to your computer and use it in GitHub Desktop.
Insertion & deletion in Singly Linked List
#include <bits/stdc++.h>
using namespace std;
typedef struct node{
int data;
struct node *next;
}node;
node* insertBegin(node *head, int n)
{
node *test = (node*)malloc(sizeof(node));
test->data = n;
test->next = NULL;
if(head != NULL)
{
test->next = head;
head = test;
}
else
{
head = test;
}
return head;
}
node* insertEnd(node *head, int n)
{
node *ptr = (node*)malloc(sizeof(node));
ptr->data = n;
ptr->next = NULL;
if(head != NULL)
{
node *test = head;
while(test->next != NULL)
test = test->next;
test->next = ptr;
}
else
{
head = ptr;
}
return head;
}
node* inserMid(node *head, int n, int pos)
{
node *ptr = (node*)malloc(sizeof(node));
ptr->data = n;
ptr->next = NULL;
node *test = head;
node *save = NULL;
if(head != NULL)
{
for(int i = 1; i < pos-1; i++)
test = test->next;
save = test->next;
test->next = ptr;
ptr->next = save;
}
return head;
}
node* del(node *head, int n)
{
node *ptr = head;
if(ptr->data == n)
{
ptr = ptr->next;
head = ptr;
}
else
{
node *save = NULL;
while(ptr != NULL)
{
if(ptr->data == n)
{
save->next = ptr->next;
break;
}
save = ptr;
ptr = ptr->next;
}
}
return head;
}
void print(node *head)
{
node *ptr = head;
while(ptr->next != NULL)
{
cout << ptr->data << " ";
ptr = ptr->next;
}
}
int main()
{
node *head = NULL;
// Insert and Beginning
for(int i = 0; i < 5; i++)
head = insertBegin(head, i);
print(head);
cout << endl;
// Insert End
for(int i = 10; i < 15; i++)
head = insertEnd(head, i);
print(head);
cout << endl;
// Insert at any position
head = inserMid(head, 99, 4);
print(head);
cout << endl;
// Deleting a node from anywhere
head = del(head, 99);
print(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment