欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java实现栈

程序员文章站 2022-06-05 14:59:35
...
public class zhan {

	// 创建头节点
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Node hear = new Node(" ");
		Lianbiao l = new Lianbiao(hear);
		Node num1 = new Node("no.1");
		l.add(num1);
		Node num2 = new Node("no.2");
		l.add(num2);
		Node num3 = new Node("no.3");
		l.add(num3);
		Node num4 = new Node("no.4");
		l.add(num4);
		Node num5 = new Node("no.5");
		l.add(num5);
		System.out.print("经过重复添加获得:");
		l.bianli();
		System.out.print("将元素内容no.6添加到后面得:");
		Node num6 = new Node("no.6");
		l.add(num6);
		l.bianli();
		System.out.print("输出元素:" + l.del().getdata() + "栈剩余元素:");
		l.bianli();
		System.out.print("输出元素:" + l.del().getdata() + "栈剩余元素:");
		l.bianli();
		System.out.print("输出元素:" + l.del().getdata() + "栈剩余元素:");
		l.bianli();
		System.out.print("输出元素:" + l.del().getdata() + "栈剩余元素:");
		l.bianli();
		System.out.print("输出元素:" + l.del().getdata() + "栈剩余元素:");
		l.bianli();
		Node num7 = new Node("no.7");
		l.add(num7);
		Node num8 = new Node("no.8");
		l.add(num8);
		Node num9 = new Node("no.9");
		l.add(num9);
		Node num10 = new Node("no.10");
		l.add(num10);
		Node num11 = new Node("no.11");
		l.add(num11);
		System.out.print("经过重复添加,栈内剩余元素:");
		l.bianli();
		System.out.print("将栈内元素全部输出");
		l.shuchu();
	}
}

class Node {
	String data;
	Node next = null;
	Node pre = null;

	Node(String data) {
		this.data = data;
	}

	public String getdata() {
		return data;
	}

	public Node getnext() {
		return next;
	}

	public void setnext(Node next) {
		this.next = next;
	}

	public Node getpre() {
		return pre;

	}

	public void setpre(Node pre) {
		this.pre = pre;
	}
}

class Lianbiao {
	Node hear = null;
	Node tail = null;
	Node prenode = null;
	int a = 0; // 记录栈长度

	Lianbiao(Node hear) {
		this.hear = hear;
		tail = hear;
		prenode = hear;
	}

	public Node gethear() {
		return hear;

	}

	// 链表元素的添加
	public void add(Node node) {
		node.setpre(prenode);
		node.setnext(null);
		prenode.setnext(node);
		prenode = node;
		a++;
	}

	// 元素的输出
	public Node del() {
		Node sc = null;
		Node n = hear;
		int i = a;
		if (a == 0) {
			System.out.print("错误!----栈空!");
		} else {
			while (i > 0) {
				n = n.getnext();
				if (i == 1) {
					prenode=n.getpre();
					n.getpre().setnext(null);
					sc = n;
				}
				i--;
			}
			a--;
		}
		return sc;
	}
	//全部输出
	public void shuchu() {
		Node sc = null;
	
		
		while(a>0){
			Node n = hear;
			int i = a;
			while (i > 0) {	
				n = n.getnext();
				if (i == 1) {
					prenode=n.getpre();
					n.getpre().setnext(null);
					sc = n;
					System.out.print(sc.getdata()+" ");
				}
				i--;
			}
			a--;
		}
	}

	// 遍历输出列表(此方法用于测试,不受规则约束,使用栈时避免使用)
	public void bianli() {
		Node n = hear;
		while (n != null) {
			System.out.print(n.getdata() + " ");
			n = n.getnext();
		}
		System.out.println();
	}

}

java实现栈

*原创作品,转载请表明出处。有建议或者问题欢迎联系我,QQ1595787997