Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active July 1, 2019 17:30
Show Gist options
  • Save manojnaidu619/6f86d054a1de4025b7ef234d7f78acdb to your computer and use it in GitHub Desktop.
Save manojnaidu619/6f86d054a1de4025b7ef234d7f78acdb to your computer and use it in GitHub Desktop.
SLL Insertions & Deletion in CPP
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
}*start=NULL;
void ins(int ele){
struct Node *p = start;
if(!p){
struct Node *temp;
temp = new Node;
temp -> data = ele;
temp -> next = NULL;
start = temp;
}else{
struct Node *temp;
temp = new Node;
temp->data = ele;
temp->next = NULL;
while(p->next){
p=p->next;
}
p->next = temp;
}
}
void display(){
struct Node *p = start;
while(p){
cout << p->data << " -> ";
p=p->next;
}
}
int count(){
int count = 0;
struct Node *p = start;
while(p){
count++;
p=p->next;
}
return count;
}
void beg(int ele){
struct Node *temp = new Node;
temp -> data = ele;
temp -> next = start;
start = temp;
}
void ins_at(int pos,int ele){
if(pos <= 1){
beg(ele);
}
else if(pos >= count()){
ins(ele);
}
else{
struct Node *p = start;
for(int i=1;i<pos-1;i++){
p=p->next;
}
struct Node *temp = new Node;
temp -> data = ele;
temp -> next = p->next;
p->next = temp;
}
}
void sorted_ins(int ele){
struct Node *x = start,*y,*temp;
if(!start){
ins(ele);
}
else if(ele <= start->data){
beg(ele);
}
else{
while(x && x->data <= ele){
y=x;
x=x->next;
}
temp = new Node;
temp->data = ele;
temp->next = y->next;
y->next = temp;
}
}
void del(int pos){
struct Node *p = start,*q;
if(pos == 1){
q = start;
start = start->next;
int x = q->data;
delete q;
cout << x << " Deleteted!" << endl;
}
else if(pos <= count()){
for(int i=1;i<pos;i++){
q=p;
p=p->next;
}
q->next = p->next;
int x = p->data;
delete p;
cout << x << " Deleted!" << endl;
}
else{
cout << "Cannot delete Node " << pos << endl;
}
}
int main(){
for(int i=1;i<=5;i++){
ins(i*2);
}
display();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment