Skip to content

Instantly share code, notes, and snippets.

@miladabc
Created July 7, 2018 16:35
Show Gist options
  • Save miladabc/a436184a2e72e4239f0dc19fce20689e to your computer and use it in GitHub Desktop.
Save miladabc/a436184a2e72e4239f0dc19fce20689e to your computer and use it in GitHub Desktop.
Singly Linked List
//Milad Abbasi
//06-07-2018
//Singly Linked List
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class List
{
Node *head, *tail;
public:
List()
{
head = NULL;
tail = NULL;
}
bool isEmpty(void)
{
return head == NULL;
}
void insertStart(int value)
{
Node *tmp = new Node;
tmp->data = value;
if(isEmpty())
{
tmp->next = NULL;
head = tail = tmp;
}
else
{
tmp->next = head;
head = tmp;
}
}
void insertEnd(int value)
{
Node *tmp = new Node;
tmp->data = value;
tmp->next = NULL;
if(isEmpty())
head = tail = tmp;
else
{
tail->next = tmp;
tail = tmp;
}
}
void insertPosition(int pos, int value)
{
Node *tmp = new Node;
tmp->data = value;
Node *current, *previous;
current = head;
for(int i = 1; i < pos; i++)
{
previous = current;
current = current->next;
}
previous->next = tmp;
tmp->next = current;
}
void deleteFirst(void)
{
if(!isEmpty())
{
Node *tmp = new Node;
tmp = head;
head = head->next;
delete tmp;
}
else
cout<<"List is empty!";
}
void deleteLast(void)
{
if(!isEmpty())
{
Node *current, *previous;
current = head;
while(current->next)
{
previous = current;
current = current->next;
}
previous->next = NULL;
tail = previous;
delete current;
}
else
cout<<"List is empty!";
}
void deletePosition(int pos)
{
if(!isEmpty())
{
Node *current, *previous;
current = head;
for (int i = 1; i < pos; i++)
{
previous = current;
current = current->next;
}
previous->next = current->next;
}
else
cout<<"List is empty!";
}
void print(void)
{
Node *tmp = new Node;
tmp = head;
while(tmp)
{
cout<<tmp->data<<"\t";
tmp = tmp->next;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment