0% found this document useful (0 votes)
30 views

Stack

Uploaded by

vijayvsi81
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Stack

Uploaded by

vijayvsi81
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Stack using singly linked list

To implement a stack using the singly linked list concept, all the singly linked list operations should
be performed based on Stack operations LIFO(last in first out) and with the help of that knowledge,
we are going to implement a stack using a singly linked list. So we need to follow a simple rule in the
implementation of a stack which is last in first out and all the operations can be performed with the
help of a top variable.

In the stack Implementation, a stack contains a top pointer. which is the “head” of the stack where
pushing and popping items happens at the head of the list. The first node has a null in the link field
and second node-link has the first node address in the link field and so on and the last node address
is in the “top” pointer.

The main advantage of using a linked list over arrays is that it is possible to implement a stack that
can shrink or grow as much as needed. Using an array will put a restriction on the maximum capacity
of the array which can lead to stack overflow. Here each new node will be dynamically allocated. so
overflow is not possible.

Stack Operations:
push(): Insert a new element into the stack i.e just insert a new element at the beginning of the
linked list.

pop(): Return the top element of the Stack i.e simply delete the first element from the linked list.

display(): Print all elements in Stack.

Push Operation:

Initialise a node

Update the value of that node by data i.e. node->data = data

Now link this node to the top of the linked list

And update top pointer to the current node

Pop Operation:

First Check whether there is any node present in the linked list or not, if not then return

Otherwise make pointer let say temp to the top node and move forward the top node by 1 step

Now free this temp node

Display Operation:

Take a temp node and initialize it with top pointer

Now start traversing temp till it encounters NULL

Simultaneously print the value of the temp node

Implementation:

#include <stdio.h>

#include <stdlib.h>

void push();

void pop();

void display();

struct node

int val;

struct node *next;

};
struct node *head;

void main ()

int choice=0;

printf("\n*********Stack operations using linked list*********\n");

printf("\n----------------------------------------------\n");

while(choice != 4)

printf("\n\nChose one from the below options...\n");

printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");

printf("\n Enter your choice \n");

scanf("%d",&choice);

switch(choice)

case 1:

push();

break;

case 2:

pop();

break;

case 3:

{
display();

break;

case 4:

printf("Exiting....");

break;

default:

printf("Please Enter valid choice ");

};

void push ()

int val;

struct node *ptr = (struct node*)malloc(sizeof(struct node));

if(ptr == NULL)

printf("not able to push the element");

else

printf("Enter the value");

scanf("%d",&val);
if(head==NULL)

ptr->val = val;

ptr -> next = NULL;

head=ptr;

else

ptr->val = val;

ptr->next = head;

head=ptr;

printf("Item pushed");

void pop()

int item;

struct node *ptr;

if (head == NULL)

printf("Underflow");

else
{

item = head->val;

ptr = head;

head = head->next;

free(ptr);

printf("Item popped");

void display()

int i;

struct node *ptr;

ptr=head;

if(ptr == NULL)

printf("Stack is empty\n");

else

printf("Printing Stack elements \n");

while(ptr!=NULL)

printf("%d\n",ptr->val);

ptr = ptr->next;

}
}

Queue Using linked list

Due to the drawbacks discussed in the previous section of this tutorial, the array implementation can
not be used for the large scale applications where the queues are implemented. One of the
alternative of array implementation is linked list implementation of queue.The storage requirement
of linked representation of a queue with n elements is o(n) while the time requirement for
operations is o(1).In a linked queue, each node of the queue consists of two parts i.e. data part and
the link part. Each element of the queue points to its immediate next element in the memory.

In the linked queue, there are two pointers maintained in the memory i.e. front pointer and rear
pointer. The front pointer contains the address of the starting element of the queue while the rear
pointer contains the address of the last element of the queue.

Implementation

#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;

};

struct node *front;

struct node *rear;

void insert();

void delete();

void display();

void main ()

int choice;
while(choice != 4)

printf("\n*************************Main Menu*****************************\n");

printf("\n=================================================================\n");

printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");

printf("\nEnter your choice ?");

scanf("%d",& choice);

switch(choice)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:

display();

break;

case 4:

exit(0);

break;

default:

printf("\nEnter valid choice??\n");

void insert()
{

struct node *ptr;

int item;

ptr = (struct node *) malloc (sizeof(struct node));

if(ptr == NULL)

printf("\nOVERFLOW\n");

return;

else

printf("\nEnter value?\n");

scanf("%d",&item);

ptr -> data = item;

if(front == NULL)

front = ptr;

rear = ptr;

front -> next = NULL;

rear -> next = NULL;

else

rear -> next = ptr;

rear = ptr;

rear->next = NULL;
}

void delete ()

struct node *ptr;

if(front == NULL)

printf("\nUNDERFLOW\n");

return;

else

ptr = front;

front = front -> next;

free(ptr);

void display()

struct node *ptr;

ptr = front;

if(front == NULL)

printf("\nEmpty queue\n");

else
{ printf("\nprinting values .....\n");

while(ptr != NULL)

printf("\n%d\n",ptr -> data);

ptr = ptr -> next;

Singly Circular Linked List

#include <stdio.h>

#include <stdlib.h>

// Structure for a node

struct Node {

int data;

struct Node* next;

};

// Function to insert a node at the

// beginning of a Circular linked list

void push(struct Node** head_ref, int data)

{
// Create a new node and make head

// as next of it.

struct Node* ptr1 = (struct Node*)malloc(sizeof(struct Node));

ptr1->data = data;

ptr1->next = *head_ref;

// If linked list is not NULL then

// set the next of last node

if (*head_ref != NULL) {

// Find the node before head and

// update next of it.

struct Node* temp = *head_ref;

while (temp->next != *head_ref)

temp = temp->next;

temp->next = ptr1;

else

// For the first node

ptr1->next = ptr1;

*head_ref = ptr1;

// Function to print nodes in a given

// circular linked list


void printList(struct Node* head)

struct Node* temp = head;

if (head != NULL) {

do {

printf("%d ", temp->data);

temp = temp->next;

} while (temp != head);

printf("\n");

// Function to delete a given node

// from the list

void deleteNode(struct Node** head, int key)

// If linked list is empty

if (*head == NULL)

return;

// If the list contains only a

// single node

if ((*head)->data == key && (*head)->next == *head) {

free(*head);

*head = NULL;
return;

struct Node *last = *head, *d;

// If head is to be deleted

if ((*head)->data == key) {

// Find the last node of the list

while (last->next != *head)

last = last->next;

// Point last node to the next of

// head i.e. the second node

// of the list

last->next = (*head)->next;

free(*head);

*head = last->next;

return;

// Either the node to be deleted is

// not found or the end of list

// is not reached

while (last->next != *head && last->next->data != key) {

last = last->next;

}
// If node to be deleted was found

if (last->next->data == key) {

d = last->next;

last->next = d->next;

free(d);

else

printf("Given node is not found in the list!!!\n");

// Driver code

int main()

// Initialize lists as empty

struct Node* head = NULL;

// Created linked list will be

// 2->5->7->8->10

push(&head, 2);

push(&head, 5);

push(&head, 7);

push(&head, 8);

push(&head, 10);

printf("List Before Deletion: ");

printList(head);
deleteNode(&head, 7);

printf("List After Deletion: ");

printList(head);

return 0;

Doubly Circular Linked List

Characteristics of Circular Doubly Linked List :


A circular doubly linked list has the following properties:
 Circular: A circular doubly linked list’s main feature is that it is circular in design.
 Doubly Linked: Each node in a circular doubly linked list has two pointers – one
pointing to the node before it and the other pointing to the node after it.
 Header Node: At the start of circular doubly linked lists, a header node or sentinel node
is frequently used. This node is used to make the execution of certain operations on the
list simpler even though it is not a component of the list’s actual contents.
Applications of Circular Doubly Linked List :
Circular doubly linked lists are used in a variety of applications, some of which include:
 Implementation of Circular Data Structures: Circular doubly linked lists are
extremely helpful in the construction of circular data structures like circular queues and
circular buffers, which are both circular in nature.
 Implementing Undo-Redo Operations: Text editors and other software programs can
use circular doubly linked lists to implement undo-redo operations.
 Music Player Playlist: Playlists in music players are frequently implemented using
circular doubly linked lists. Each song is kept as a node in the list in this scenario, and
the list can be circled to play the songs in the order they are listed.
 Cache Memory Management: To maintain track of the most recently used cache
blocks, circular doubly linked lists are employed in cache memory management.
#include<stdio.h>

#include<stdlib.h>

// structure of the node

struct node

struct node* prev;

int data;

struct node* next;

};

// global declaration of head node

struct node* head = NULL;

// function prototyping

struct node* create(int);

void insert_begin(int);

void insert_end(int);

void insert_mid(int, int);

void delete_begin();

void delete_end();

void delete_mid();

int search(int);
void update(int, int);

void sort();

int list_size();

void display();

void display_reverse(struct node*);

int get_data();

int get_position();

int main()

char user_active = 'Y';

int user_choice;

int data, position;

while(user_active == 'Y' || user_active == 'y')

printf("\n\n------ Circular Doubly Linked List -------\n");

printf("\n1. Insert a node at beginning");

printf("\n2. Insert a node at end");

printf("\n3. Insert a node at given position");

printf("\n\n4. Delete a node from beginning");

printf("\n5. Delete a node from end");

printf("\n6. Delete a node from given position");

printf("\n\n7. Print list from beginning");

printf("\n8. Print list from end");

printf("\n9. Search a node data");

printf("\n10. Update a node data");


printf("\n11. Sort the list");

printf("\n12. Exit");

printf("\n\n------------------------------\n");

printf("\nEnter your choice: ");

scanf("%d", &user_choice);

printf("\n------------------------------\n");

switch(user_choice)

case 1:

printf("\nInserting a node at beginning");

data = get_data();

insert_begin(data);

break;

case 2:

printf("\nInserting a node at end");

data = get_data();

insert_end(data);

break;

case 3:

printf("\nInserting a node at the given position");

data = get_data();

position = get_position();

insert_mid(position, data);
break;

case 4:

printf("\nDeleting a node from beginning\n");

delete_begin();

break;

case 5:

printf("\nDeleting a node from end\n");

delete_end();

break;

case 6:

printf("\nDelete a node from given position\n");

position = get_position();

delete_mid(position);

break;

case 7:

printf("\nPrinting the list from beginning\n\n");

display();

break;

case 8:

printf("\nPrinting the list from end\n\n");

if (head == NULL)

{
printf("\n\tList is Empty!\n");

} else {

display_reverse(head);

break;

case 9:

printf("\nSearching the node data");

data = get_data();

if (search(data) == 1) {

printf("\n\tNode Found\n");

} else {

printf("\n\tNode Not Found\n");

break;

case 10:

printf("\nUpdating the node data");

data = get_data();

position = get_position();

update(position, data);

break;

case 11:

sort();

printf("\nList was sorted\n");

break;
case 12:

printf("\nProgram was terminated\n\n");

return 0;

default:

printf("\n\tInvalid Choice\n");

printf("\n...............................\n");

printf("\nDo you want to continue? (Y/N) : ");

fflush(stdin);

scanf(" %c", &user_active);

return 0;

// creates a new node

struct node* create(int data)

struct node* new_node = (struct node*) malloc (sizeof(struct node));

if (new_node == NULL)

printf("\nMemory can't be allocated\n");

return NULL;

}
new_node->data = data;

new_node->next = NULL;

new_node->prev = NULL;

return new_node;

// insert a new node at the beginning of the list

void insert_begin(int data)

struct node* new_node = create(data);

if (new_node)

// if list is empty

if (head == NULL)

new_node->next = new_node;

new_node->prev = new_node;

head = new_node;

return;

head->prev->next = new_node;

new_node->prev = head->prev;

new_node->next = head;

head->prev = new_node;
head = new_node;

// inserts a new node at the end

void insert_end(int data)

struct node* new_node = create(data);

if (new_node)

if (head == NULL)

new_node->next = new_node;

new_node->prev = new_node;

head = new_node;

return;

head->prev->next = new_node;

new_node->prev = head->prev;

new_node->next = head;

head->prev = new_node;

// inserts node at the given position

void insert_mid(int position, int data)


{

// checking if the position is valid or not

if (position <= 0)

printf("\nInvalid Position\n");

} else if (head == NULL && position > 1) {

printf("\nInvalid Position\n");

} else if (head != NULL && position > list_size()) {

printf("\nInvalid Position\n");

} else if (position == 1) {

insert_begin(data);

} else {

struct node *new_node = create(data);

if (new_node != NULL) {

struct node *temp = head, *prev = NULL;

int i = 1;

// traverse the list to the given position

while (++i <= position) {

prev = temp;

temp = temp->next;

// update the prev node to the new noe

prev->next = new_node;
// update the new node to the temp (position node)

new_node->next = temp;

void delete_begin()

if (head == NULL) {

printf("\nList is Empty\n");

return;

} else if (head->next == head) {

free(head);

head = NULL;

return;

struct node* temp = head;

head->prev->next = head->next;

head->next->prev = head->prev;

head = head->next;

free(temp);

temp = NULL;

// deletes the node from the end of the list


void delete_end()

if (head == NULL) {

printf("\nList is Empty\n");

return;

} else if (head->next == head) {

free(head);

head = NULL;

return;

struct node* last_node = head->prev;

last_node->prev->next = head;

head->prev = last_node->prev;

free(last_node);

last_node = NULL;

// deletes the node from the given position

void delete_mid(int position)

if (position <= 0) {

printf("\n Invalid Position \n");

else if (position > list_size()) {


printf("\n Invalid position \n");

else if (position == 1) {

delete_begin();

else if (position == list_size()) {

delete_end();

else {

struct node *temp = head;

struct node *prev = NULL;

int i = 1;

while (i < position) {

prev = temp;

temp = temp->next;

i += 1;

prev->next = temp->next;

temp->next->prev = prev;

free(temp);

temp = NULL;

// search the node with the given key item

int search(int key)


{

if (head == NULL) {

printf("\n Not Found \n");

return 0;

struct node* temp = head;

do

if (temp->data == key) {

return 1;

temp = temp->next;

} while (temp != head);

return 0;

// updates the data of the given node position

void update(int position, int new_value)

if (head == NULL) {

printf("\n List is Empty \n");

return;

} else if (position <= 0 || position > list_size()) {

printf("\nInvalid position\n");

return;
}

struct node* temp = head;

int i = 0;

while (++i < position) {

temp = temp->next;

temp->data = new_value;

// sorts the linked list data using insertion sort

void sort()

if (head == NULL) {

printf("\nList is Empty\n");

return;

struct node* temp1 = head;

struct node* temp2 = head;

int key = 0, value;

do {

temp2 = temp1->next;

while(temp2 != head)
{

if (temp1->data > temp2->data)

value = temp1->data;

temp1->data = temp2->data;

temp2->data = value;

temp2 = temp2->next;

temp1 = temp1->next;

}while (temp1->next != head);

// display the list

void display()

if (head == NULL) {

printf("\nList is empty!\n");

return;

struct node* temp = head;

do {

printf("%d ", temp->data);

temp = temp->next;
} while (temp != head);

// display the list from end to start

void display_reverse(struct node* temp)

if (temp->next == head) {

printf("%d ", temp->data);

return;

display_reverse(temp->next);

printf("%d ", temp->data);

// calculate the size of the list

int list_size()

if (head == NULL) {

return 0;

struct node* temp = head;

int count = 0;

do {

count += 1;
temp = temp->next;

} while (temp != head);

return count;

int get_data()

int data;

printf("\n\nEnter Data: ");

scanf("%d", &data);

return data;

int get_position()

int position;

printf("\n\nEnter Position: ");

scanf("%d", &position);

return position;

You might also like