Single Linked List (Push and Pop)

Implement a stack using linked list concept. all the linked list operations perform based on Stack operations LIFO(last in first out) and with the help of that knowledge we are going to implement a stack using  linked list. 

Stack operations:
push() : Insert the element into linked list nothing but which is the top node of Stack.
pop() : Return top element from the Stack and move the top pointer to the second node of linked list or Stack

Example of push and pop using linked list in c:

Single linked list:

  • push_front: 5, 3, 7, 9 the output are: 9 ->7 ->3 -> 5 -> NULL
  • void push_front(int number){
  • current=(struct data*)malloc(sizeof(struct data));
  • current->number = number; 
  • if(head==NULL){
  • head=tail=current;
  • tail->next=NULL;
  • }
  • else{
  • current->next=head;
  • head=current;
  • }
  • }
void show (){
current=head;
while(current!=NULL){
printf("%d ",current->number);
current=current->next;
}
}

  • int main (){
  •  push_front(5);
  •  push_front(3);
  •  push_front(9);
  •  push_front(7);
  • show();
  • getchar();
  • return 0;
  • }

  • push_back: 200, 10, 5, 50 the output are: 200 ->50 ->10 ->10 -> NULL
  • void push_back (int number){
  • current=(struct data*)malloc(sizeof(struct data));
  • current->number = number; 
  • if(head==NULL){
  • head=tail=current;
  • tail->next=NULL;
  • }
  • else{
  • tail->next=current;
  • tail=current;
  • tail->next=NULL;
  • }
  • }

  • void show (){
  • current=head;
  • while(current!=NULL){
  • printf("%d ",current->number);
  • current=current->next;
  • }
  • }
  • int main (){
  •  push_back(200);
  •  push_back(10);
  •  push_back(5);
  •  push_back(50);
  • show();
  • getchar();
  • return 0;
  • }

  • pop_front : 10,2,3,4,5 the output are  : 2->3->4->5->NULL
  • void pop_front(){
  • if(head!=NULL){
  • current=head;
  • head=head->next;
  • free(current);
  • }
  • }
  • void show (){
  • current=head;
  • while(current!=NULL){
  • printf("%d ",current->number);
  • current=current->next;
  • }
  • }

  • int main (){
  •  pop_front(10);

  • show();
  • getchar();
  • return 0;
  • }



Referensi:
https://www.geeksforgeeks.org/vectorpush_back-vectorpop_back-c-stl/
https://socs.binus.ac.id/2017/03/15/single-linked-list/
https://www.geeksforgeeks.org/implement-a-stack-using-singly-linked-list/

















Komentar

Postingan populer dari blog ini

AVL Tree

Binary Search Tree

Heaps dan Tries