Skip to content

Updated StackOfLinkedList.java #711

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 5, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 25 additions & 24 deletions DataStructures/Stacks/StackOfLinkedList.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/

// An implementation of a Stack using a Linked List
Expand All @@ -25,9 +23,7 @@ public static void main(String[] args) {
stack.pop();

System.out.println("Top element of stack currently is: " + stack.peek());

}

}

// A node class
Expand All @@ -44,66 +40,71 @@ public Node(int data) {

/**
* A class which implements a stack using a linked list
*
* <p>
* Contains all the stack methods : push, pop, printStack, isEmpty
**/

class LinkedListStack {

Node head = null;
int size = 0;

public void push(int x) {
Node n = new Node(x);
if (getSize() == 0) {
if (head == null) {
head = n;
}
else {
} else {
Node temp = head;
n.next = temp;
head = n;
}
size++;
}

public void pop() {
if (getSize() == 0) {
if (head == null) {
System.out.println("Empty stack. Nothing to pop");
}

Node temp = head;
head = head.next;
size--;

System.out.println("Popped element is: " + temp.data);
}

public int peek() {
if (getSize() == 0) {
return -1;
}

return head.data;
if (head == null) {
return -1;
}
return head.data;
}

public void printStack() {

Node temp = head;
System.out.println("Stack is printed as below: ");
while (temp != null) {
System.out.println(temp.data + " ");
if (temp.next == null) {
System.out.print(temp.data);
} else {
System.out.print(temp.data + " -> ");
}
temp = temp.next;
}
System.out.println();

}

public boolean isEmpty() {
return getSize() == 0;
return head == null;
}

public int getSize() {
return size;
if (head == null)
return 0;
else {
int size = 1;
Node temp = head;
while (temp.next != null) {
temp = temp.next;
size++;
}
return size;
}
}

}