Stack Using Linked List

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

1.

Stack using
linked list
import java.io.*;
class Stack1
{
Stack1 top,next,prev;
int data;
Stack1()
{
data=0;
next=prev=null;
}
Stack1(int d)
{
data=d;
next=prev=null;
}
void push(int n)
{
Stack1 nn;
nn=new Stack1(n);
if(top==null)
top=nn;
else
{
nn.next=top;
top.prev=nn;
top=nn;
}
}
int pop()
{
int k=top.data;
if(top.next==null)
{
top=null;
return k;
}
else
{
top=top.next;
top.prev=null;
return k;
}
}
boolean isEmpty()
{

if(top==null)
return true;
else
return false;
}

void display()
{
Stack1 ptr;
for(ptr=top;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
public static void main(String args[ ])throws Exception
{
int x; int ch;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Stack1 a=new Stack1();
do{
System.out.println("enter 1 for pushing");
System.out.println("enter 2 for poping");
System.out.println("enter 3 for isEmpty");
System.out.println("enter 4 for display");
System.out.println("Enter 0 for exit");
System.out.println("enter ur choice ");
ch=Integer.parseInt(b.readLine()); switch(ch)
{
case 1:System.out.println("enter element to insert");
int e=Integer.parseInt(b.readLine());
a.push(e);
break;
case 2:if(!a.isEmpty())
{
int p=a.pop();
System.out.println("deleted element is "+p);
}
else
{
System.out.println("stack is empty");
}
break;
case 3:System.out.println(a.isEmpty());
break;
case 4:if(!a.isEmpty())
{
a.display();
}
else
{

System.out.println("list is empty");
}

while(ch!=0);
}
}

Output:
2. //Queue using Linked list

import java.io.*;
class Qlnk
{
Qlnk front,rear,next;
int data;
Qlnk()
{
data=0;
next=null;
}
Qlnk(int d)
{
data=d;

next=null;
}
Qlnk getFront()
{
return front;
}
Qlnk getRear()
{
return rear;
}
void insertelm(int item)
{
Qlnk nn;
nn=new Qlnk(item);
if(isEmpty())
{
front=rear=nn;
}
else
{
rear.next=nn;
rear=nn;
}
}
int delelm()
{
if(isEmpty())
{
System.out.println("deletion failed");
return -1;
}
else
{
int k=front.data;
if(front!=rear)
front=front.next;
else rear=front=null;
return k;
}
}
boolean isEmpty()
{
if(rear==null)
return
true; else
return false;
}
int size()
{
Qlnk ptr;
int cnt=0;
for(ptr=front;ptr!=null;ptr=ptr.next)
cnt++;
return cnt;
}
void display()
{
Qlnk ptr; if(!
isEmpty())
{
for(ptr=front;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
else
System.out.println("q is empty");
}
public static void main(String arr[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Qlnk m=new Qlnk();
int ch;
do
{
System.out.println("enter 1 for insert");
System.out.println("enter 2 for
deletion");
System.out.println("enter 3 for
getFront");
System.out.println("enter 4 for getRear");
System.out.println("enter 5 for size");
System.out.println("enter 6 for display");
System.out.println("enter 0 for exit");
System.out.println("enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("enter ele to insert");
int item=Integer.parseInt(br.readLine());
m.insertelm(item);
break;

case 2:
int k=m.delelm();
System.out.println("deleted ele is "+k);
break;

case 3:
System.out.println("front index is"+(m.getFront()).data);
break;

case 4:
System.out.println("rear index is"+(m.getRear()).data);
break;

case 5:
System.out.println("size is"+m.size());
break;

case 6:
m.display();break;
}

}while(ch!=0);
}
}

Output:
3. implementation of De-queue
(using circular array)
 
// A structure to represent a Deque
class Deque {
    static final int MAX = 100;
    int arr[];
    int front;
    int rear;
    int size;
 
    public Deque(int size)
    {
        arr = new int[MAX];
        front = -1;
        rear = 0;
        this.size = size;
    }
 
    /*// Operations on Deque:
    void  insertfront(int key);
    void  insertrear(int key);
    void  deletefront();
    void  deleterear();
    bool  isFull();
    bool  isEmpty();
    int  getFront();
    int  getRear();*/
 
    // Checks whether Deque is full or not.
    boolean isFull()
    {
        return ((front == 0 && rear == size - 1)
                || front == rear + 1);
    }
 
    // Checks whether Deque is empty or not.
    boolean isEmpty() { return (front == -1); }
 
    // Inserts an element at front
    void insertfront(int key)
    {
        // check whether Deque if  full or not
        if (isFull()) {
            System.out.println("Overflow");
            return;
        }
 
        // If queue is initially empty
        if (front == -1) {
            front = 0;
            rear = 0;
        }
 
        // front is at first position of queue
        else if (front == 0)
            front = size - 1;
 
        else // decrement front end by '1'
            front = front - 1;
 
        // insert current element into Deque
        arr[front] = key;
    }
 
    // function to inset element at rear end
    // of Deque.
    void insertrear(int key)
    {
        if (isFull()) {
            System.out.println(" Overflow ");
            return;
        }
 
        // If queue is initially empty
        if (front == -1) {
            front = 0;
            rear = 0;
        }
 
        // rear is at last position of queue
        else if (rear == size - 1)
            rear = 0;
 
        // increment rear end by '1'
        else
            rear = rear + 1;
 
        // insert current element into Deque
        arr[rear] = key;
    }
 
    // Deletes element at front end of Deque
    void deletefront()
    {
        // check whether Deque is empty or not
        if (isEmpty()) {
            System.out.println("Queue Underflow\n");
            return;
        }
 
        // Deque has only one element
        if (front == rear) {
            front = -1;
            rear = -1;
        }
        else
            // back to initial position
            if (front == size - 1)
            front = 0;
 
        else // increment front by '1' to remove current
            // front value from Deque
            front = front + 1;
    }
 
    // Delete element at rear end of Deque
    void deleterear()
    {
        if (isEmpty()) {
            System.out.println(" Underflow");
            return;
        }
 
        // Deque has only one element
        if (front == rear) {
            front = -1;
            rear = -1;
        }
        else if (rear == 0)
            rear = size - 1;
        else
            rear = rear - 1;
    }
 
    // Returns front element of Deque
    int getFront()
    {
        // check whether Deque is empty or not
        if (isEmpty()) {
            System.out.println(" Underflow");
            return -1;
        }
        return arr[front];
    }
 
    // function return rear element of Deque
    int getRear()
    {
        // check whether Deque is empty or not
        if (isEmpty() || rear < 0) {
            System.out.println(" Underflow\n");
            return -1;
        }
        return arr[rear];
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        Deque dq = new Deque(5);
 
          // Function calls
        System.out.println(
            "Insert element at rear end  : 5 ");
        dq.insertrear(5);
 
        System.out.println(
            "insert element at rear end : 10 ");
        dq.insertrear(10);
 
        System.out.println("get rear element : "
                           + dq.getRear());
 
        dq.deleterear();
        System.out.println(
            "After delete rear element new rear become : "
            + dq.getRear());
 
        System.out.println(
            "inserting element at front end");
        dq.insertfront(15);
 
        System.out.println("get front element: "
                           + dq.getFront());
 
        dq.deletefront();
 
        System.out.println(
            "After delete front element new front become : "
            + +dq.getFront());
    }
}

Output
Insert element at rear end : 5
insert element at rear end : 10
get rear element 10
After delete rear element new rear become 5
inserting element at front end
get front element 15
After delete front element new front become 5

4. Implementation of Deque using


doubly linked list
import java.util.*;
class GFG
{
 
  // Node of a doubly linked list
  static class Node
  {
    int data;
    Node prev, next;
 
    // Function to get a new node
    static Node getnode(int data)
    {
      Node newNode = new Node();
      newNode.data = data;
      newNode.prev = newNode.next = null;
      return newNode;
    }
  };
 
  // A structure to represent a deque
  static class Deque {
    Node front;
    Node rear;
    int Size;
 
    Deque()
    {
      front = rear = null;
      Size = 0;
    }
 
    // Function to check whether deque
    // is empty or not
    boolean isEmpty() { return (front == null); }
 
    // Function to return the number of
    // elements in the deque
    int size() { return Size; }
 
    // Function to insert an element
    // at the front end
    void insertFront(int data)
    {
      Node newNode = Node.getnode(data);
      // If true then new element cannot be added
      // and it is an 'Overflow' condition
      if (newNode == null)
        System.out.print("OverFlow\n");
      else {
        // If deque is empty
        if (front == null)
          rear = front = newNode;
 
        // Inserts node at the front end
        else {
          newNode.next = front;
          front.prev = newNode;
          front = newNode;
        }
 
        // Increments count of elements by 1
        Size++;
      }
    }
 
    // Function to insert an element
    // at the rear end
    void insertRear(int data)
    {
      Node newNode = Node.getnode(data);
      // If true then new element cannot be added
      // and it is an 'Overflow' condition
      if (newNode == null)
        System.out.print("OverFlow\n");
      else {
        // If deque is empty
        if (rear == null)
          front = rear = newNode;
 
        // Inserts node at the rear end
        else {
          newNode.prev = rear;
          rear.next = newNode;
          rear = newNode;
        }
 
        Size++;
      }
    }
 
    // Function to delete the element
    // from the front end
    void deleteFront()
    {
      // If deque is empty then
      // 'Underflow' condition
      if (isEmpty())
        System.out.print("UnderFlow\n");
 
      // Deletes the node from the front end and makes
      // the adjustment in the links
      else {
        Node temp = front;
        front = front.next;
 
        // If only one element was present
        if (front == null)
          rear = null;
        else
          front.prev = null;
 
        // Decrements count of elements by 1
        Size--;
      }
    }
 
    // Function to delete the element
    // from the rear end
    void deleteRear()
    {
      // If deque is empty then
      // 'Underflow' condition
      if (isEmpty())
        System.out.print("UnderFlow\n");
 
      // Deletes the node from the rear end and makes
      // the adjustment in the links
      else {
        Node temp = rear;
        rear = rear.prev;
 
        // If only one element was present
        if (rear == null)
          front = null;
        else
          rear.next = null;
 
        // Decrements count of elements by 1
        Size--;
      }
    }
 
    // Function to return the element
    // at the front end
    int getFront()
    {
      // If deque is empty, then returns
      // garbage value
      if (isEmpty())
        return -1;
      return front.data;
    }
 
    // Function to return the element
    // at the rear end
    int getRear()
    {
 
      // If deque is empty, then returns
      // garbage value
      if (isEmpty())
        return -1;
      return rear.data;
    }
 
    // Function to delete all the elements
    // from Deque
    void erase()
    {
      rear = null;
      while (front != null) {
        Node temp = front;
        front = front.next;
      }
      Size = 0;
    }
  }
 
  // Driver program to test above
  public static void main(String[] args)
  {
    Deque dq = new Deque();
    System.out.print(
      "Insert element '5' at rear end\n");
    dq.insertRear(5);
 
    System.out.print(
      "Insert element '10' at rear end\n");
    dq.insertRear(10);
    System.out.print("Rear end element: " + dq.getRear()
                     + "\n");
    dq.deleteRear();
    System.out.print(
      "After deleting rear element new rear"
      + " is: " + dq.getRear() + "\n");
    System.out.print(
      "Inserting element '15' at front end \n");
    dq.insertFront(15);
    System.out.print(
      "Front end element: " + dq.getFront() + "\n");
 
    System.out.print("Number of elements in Deque: "
                     + dq.size() + "\n");
    dq.deleteFront();
    System.out.print("After deleting front element new "
                     + "front is: " + dq.getFront()
                     + "\n");
  }
}
Output
Insert element '5' at rear end
Insert element '10' at rear end
Rear end element: 10
After deleting rear element new rear is: 5
Inserting element '15' at front end
Front end element: 15
Number of elements in Deque: 2
After deleting front element new front is: 5

5. Program to implement Priority Queue


// using Arrays

import java.util.*;
 
// Structure for the elements in the
// priority queue
class item {
  public int value;
  public int priority;
};
 
class GFG {
 
  // Store the element of a priority queue
  static item[] pr = new item[100000];
 
  // Pointer to the last index
  static int size = -1;
  // Function to insert a new element
  // into priority queue
  static void enqueue(int value, int priority)
  {
    // Increase the size
    size++;
 
    // Insert the element
    pr[size] = new item();
    pr[size].value = value;
    pr[size].priority = priority;
  }
 
  // Function to check the top element
  static int peek()
  {
    int highestPriority = Integer.MIN_VALUE;
    int ind = -1;
 
    // Check for the element with
    // highest priority
    for (int i = 0; i <= size; i++) {
 
      // If priority is same choose
      // the element with the
      // highest value
      if (highestPriority == pr[i].priority
          && ind > -1
          && pr[ind].value < pr[i].value) {
        highestPriority = pr[i].priority;
        ind = i;
      }
      else if (highestPriority < pr[i].priority) {
        highestPriority = pr[i].priority;
        ind = i;
      }
    }
 
    // Return position of the element
    return ind;
  }
 
  // Function to remove the element with
  // the highest priority
  static void dequeue()
  {
    // Find the position of the element
    // with highest priority
    int ind = peek();
 
    // Shift the element one index before
    // from the position of the element
    // with highest priority is found
    for (int i = ind; i < size; i++) {
      pr[i] = pr[i + 1];
    }
 
    // Decrease the size of the
    // priority queue by one
    size--;
  }
 
  public static void main(String[] args)
  {
    // Function Call to insert elements
    // as per the priority
    enqueue(10, 2);
    enqueue(14, 4);
    enqueue(16, 4);
    enqueue(12, 3);
 
    // Stores the top element
    // at the moment
    int ind = peek();
 
    System.out.println(pr[ind].value);
 
    // Dequeue the top element
    dequeue();
 
    // Check the top element
    ind = peek();
    System.out.println(pr[ind].value);
 
    // Dequeue the top element
    dequeue();
 
    // Check the top element
    ind = peek();
    System.out.println(pr[ind].value);
  }
}

Output
16
14
12

You might also like