0% found this document useful (0 votes)
4 views3 pages

Java Stack Implementation with Linked List

The document contains a Java implementation of a stack using a singly linked list. It includes methods for pushing, popping, peeking, checking if the stack is empty, and deleting the stack. The main method demonstrates the functionality of the stack with sample operations.

Uploaded by

bibek singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Java Stack Implementation with Linked List

The document contains a Java implementation of a stack using a singly linked list. It includes methods for pushing, popping, peeking, checking if the stack is empty, and deleting the stack. The main method demonstrates the functionality of the stack with sample operations.

Uploaded by

bibek singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

package Stack;

public class Stack_LL {


public Node head;
public Node tail;
public int size;

public class Node {


public int value;
public Node next;
}

public Node createSinglyLinkedList(int nodeValue) {


Node node = new Node();
[Link] = null;
[Link] = nodeValue;
head = node;
tail = node;
size = 1;
return head;
}

// Push Method TC:O(1) SC:O(1)


public void push(int value) {
Node node = new Node();
[Link] = value;
if (head == null) {
createSinglyLinkedList(value);
[Link]("Inserted " + value + " in Stack ");
return;
} else {
[Link] = head;
head = node;
[Link]("Inserted " + value + " in Stack ");
}
}

// isEmpty TC:O(1) SC:O(1)


public boolean isEmpty() {
if (head == null) {
return true;
} else {
return false;
}
}
// Pop Method TC:O(1) SC:O(1)
public int pop() {
int result = -1;
if (isEmpty()) {
[Link]("The Stack is Empty!");
} else {
result = [Link];
head = [Link];
size--;
}
if (size == 0) {
tail = null;
}
return result;
}

// Peek Method TC:O(1) SC:O(1)


public int peek() {
int result = -1;
if (isEmpty()) {
[Link]("The Stack is Empty!");
return result;
} else {
result = [Link];
return result;
}
}

// Delete Method TC:O(1) SC:O(1)


public void deleteStack() {
head = null;
[Link]("The Stack is deleted!");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Stack_LL SLL = new Stack_LL();
[Link](1);
[Link](2);
[Link](3);
boolean result = [Link]();
[Link](result);
int result1 = [Link]();
[Link](result1);
int result2 = [Link]();
[Link](result2);
[Link]();

}
}

OUTPUT:

You might also like