Generate a stack with a linked list

package  stack;

 

/**

 * define a node

 * @author Administrator

 *

 */

class Node{

Node next= null;

int data ; 

public Node(intdata){ 

this.data = data;

}

}

 

/**

 * Create a stack with a linked list

 * @author Administrator

 *

 */

publicclass Stack { 

Node top = null;

/**

 * Determine if the linked list is empty

 * @return

 */

publicboolean isEmpty(){ 

returntop == null; 

}

/**

 * add element to stack

 */

publicvoid push(intdata){  

Node node = new Node(data);

node.next = top;

top = node;

}

/**

 * 从栈中取元素

 */

public int pop(){

if(this.isEmpty()){

return (Integer) null;

 }

int data = top.data;

top = top.next;

return data;

}

/**

 * 取栈的峰值

 * @return

 */

public int peek(){

if(this.isEmpty()){

return (Integer) null;

 }

return top.data;

}

/**

 * 返回栈中的元素个数

 * @return

 */

public int size(){

int size = 0;

Node tmp = top;

while(tmp!=null){

size++;

tmp = tmp.next;

}

return size;

}

/**

 * 打印栈

 */

public void printStack(){

Node tmp = top;

while(tmp != null){

System.out.println(tmp.data);

tmp = tmp.next;

}

}

public static void main(String[] args) {

Stack stack = new Stack();

stack.push(2);

stack.push(1);

stack.push(4);

stack.push(5);

stack.push(3);

System.out.println("打印栈:");

stack.printStack();

System.out.println("栈的大小:");

System.out.println(stack.size());;

System.out.println("取出一个元素:");

System.out.println(stack.pop());

}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326049464&siteId=291194637
Recommended