Singly Linked List
Singly Linked List
StringLinkedList l1;
l1.addFront(“Abc”);
L1.removeFront();
StringNode n;
n.elem n.next
StringNode *head=NULL
Head =0
head = new StringNode()
Head
100 elem next
head->elem
head->next
Singly linked list
Destructor of linked list
Node *p=Null;
while(head!=NULL)
{
p=head;
head=head->next;
delete p;
}
Copy Constructor
• Head 1->2->3->4
• l2.head 1->2->3->4
LinkedList l2(l1); l2.head=l1.head;
LinkedList(const LinkedList &l1)
{
P=l1.head;
Head=null;
while(p!=null)
{ newnode = new IntNode;
newnode->elem=p->elem;
newnode->next=null;
if (head==NULL) { head=newnode;p1=head;}
else
{p1->next=newnode;
p1=p1->next;
}
p=p->next;
}
Adding the node at the front
Removing node from the front
Display the linked list
void IntLinkedList::display() int IntLinkedList::count()
{ {
if(head==NULL) cout<< "Empty list ";
int count=0;
else {
IntNode* pt=head; IntNode* ptr=head;
while(pt!=NULL) while(ptr!=NULL)
{ {
// Printing the current
count++;
cout<<pt->elem;
// moving to next element ptr=ptr->next;
pt=pt->next; }
} return count;
}
}
1->2->3->10
2->4->6->20
Add at last
void LinkedList::addLast(int x)
{ IntNode *p = new IntNode;
p->elem=x;
p->next=NULL;
IntNode *temp=head;
if (empty()) {head=p; return;}
while(temp->next!=NULL) temp=temp->next;
temp->next= p;
}
Insert at a position
1-> 2-> 5-> 10
3N
}
Delete an element a given pos
• 1->2->6->5->10
• 1->2-> 5->10
• delete(pos=3)
delete(int pos)
{
ptr = head;
if (head==0) throw “Empty List. Deletion not possible”;
if (pos==1)
{
old=head;
head= old->next; delete old;;return;}
count=1;
while(ptr!=NULL && count<pos-1)
{ ptr=ptr->next;
count++;
}
if (ptr==NULL) throw “Invalid Position”;
intnode *old=ptr->next;
p-tr>next= old->next;
delete old;
Delete a given value
• 1->2->6->5->10
• delete(value=5)
delete(int value)
{
if (head==0) throw “Empty List. Deletion not possible”;
ptr = head;
prev =null;
while(ptr!=Null && ptr->elem!=value)
{
prev=ptr;
ptr=ptr->next;
}
if (ptr==NULL) throw “Invalid value”;
if (prev==null) head=head->next;
else prev->next= ptr->next;
delete ptr;
}
Class to represent linkedlist
Class LinkedList
{ IntNode *head,*tail;
public:
LinkedList(){ head=tail=0;}
void addFront(int x);
void addTail(int x);
void removeTail();
void removeHead();
void display();
int count();
void delete(int pos)
void delete(int value)
void insert(pos, value);
}
• LinkedList l1;
• L1.addFront(2) head -> 2
• tail
• L1.addFront(3) 3->2
addFront
l1
LinkedList l1;
Head Tail
NULL NULL
l1.addFront(5)
l1.addFront(5)
p p p1 p p1 p p1 p p1 p1
if (empty()) return;
p=head;
p1 = head->next;
if (p1==NULL) return;
while(p1!=NULL){
p2=p1->next;
p1->next =p;
p = p1;
p1 = p2;
}
head->next=NULL;
tail = head;
head= p;
return;