java 单链表实现栈

package com.company;

public class Main {
//用链表模拟栈
public static void main(String[] args) {
// write your code here
LinkedStake ls = new LinkedStake(4);
ls.push("aa");
ls.push("aB");
ls.push("Ca");
ls.push("Da");

ls.toList();

System.out.println("++++++++++");
ls.pop();
System.out.println("______");

ls.toList();
System.out.println("__ssss____");

}

}
class Node {
public String val;
public Node next;
public Node(String str){
this.val = str;
}
}
class ArrayLinked{
public String val ;

public Node next;
//设置一个头节点
public Node head = new Node("");



public void add(String val){


if(head.next != null){
Node temp = head.next;
head.next = new Node(val);
head.next.next = temp;
}else{
head.next = new Node(val);
}

}
//getLast
public String pop(){
String val = "";
if(head.next != null){
val = head.next.val;
Node temp2 = head.next.next;
head.next = temp2;
}

return val;
}
public void toList(){
Node temp = head;
while(temp.next!= null){

System.out.printf(temp.next.val+"\t");


temp = temp.next;
}
}

}

class LinkedStake{

public ArrayLinked arrayLink = new ArrayLinked();
//设置栈的相关属性
public int top = -1;
public int maxSize;


//初始化
public LinkedStake(int size){
this.maxSize = size;
}
//栈满判断
public boolean isFull(){
return top ==maxSize-1;
}
//栈空判断
public boolean isEmpty(){
return top ==-1;
}
//添加push方法
public void push(String val){
//先判断栈满情况
if(isFull()){
System.out.println("栈满了");
//throw new RuntimeException("栈满了");
}else{
//在链表的头部第一个位置擦插入,因为第一个是最先访问到的
arrayLink.add(val);
top++;
}
}
//取出元素方法
public String pop() {
//先判断栈满情况
String value = "";
if (isEmpty()) {
System.out.println("栈空了");
} else {
//在链表的头部第一个位置擦插入,因为第一个是最先访问到的
top--;
value = arrayLink.pop();
}
return value;
}
public void toList(){
arrayLink.toList();
}

}

java 单链表实现栈

上一篇:XML DOM HTMLElement 对象


下一篇:QT高级编程技巧(二)-- 编写多线程和并发应用