1 Star 0 Fork 0

蔡茂昌 / Algorithms-implemented-in-Java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
StackOfLinkedList.java 1.75 KB
一键复制 编辑 原始数据 按行查看 历史
DESKTOP-0VAEMFL\joaom 提交于 2017-10-28 13:05 . Fixed Merge changes
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
// An implementation of a Stack using a Linked List
class StackOfLinkedList {
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.printStack();
System.out.println("Size of stack currently is: " + stack.getSize());
stack.pop();
stack.pop();
}
}
// A node class
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
/**
* A class which implements a stack using a linked list
*
* 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) {
head = n;
}
else {
Node temp = head;
n.next = temp;
head = n;
}
size++;
}
public void pop() {
if (getSize() == 0) {
System.out.println("Empty stack. Nothing to pop");
}
Node temp = head;
head = head.next;
size--;
System.out.println("Popped element is: " + temp.data);
}
public void printStack() {
Node temp = head;
System.out.println("Stack is printed as below: ");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public boolean isEmpty() {
return getSize() == 0;
}
public int getSize() {
return size;
}
}
Java
1
https://gitee.com/edmondcmc/Algorithms-implemented-in-Java.git
git@gitee.com:edmondcmc/Algorithms-implemented-in-Java.git
edmondcmc
Algorithms-implemented-in-Java
Algorithms-implemented-in-Java
master

搜索帮助