java实现用自定义单链表模拟栈

//定义链表
public class Liststack {
	int num;
	Liststack next; // 表示链表的下一个节点

	public Liststack(int num) {
		this.num = num;
	}

	public String toString() {
		return "Liststack [num=" + num + "]";
	}
}
//定义栈
class Stack1 {
	int max; // 栈的最大容量
	int i = 0; // 标志此时元素在栈中的位置
 
	public Stack1(int max) {
		this.max = max;
	}

	Liststack head = new Liststack(0); // 链表的头节点
	//压栈
	public void add(Liststack l) {
		Liststack temp = head; // 定义临时变量指向头节点
		if (i == max) {
			System.out.println("栈已经满了");
			return;
		}
		while (true) {
			if (temp.next == null) { // 遍历到链表最后
				break;
			}
			temp = temp.next; // 后移
		}
		i++;
		temp.next = l;
	}
	//弹栈
	public void pop() {
		Liststack temp = head;
		if (temp == null) {
			System.out.println("栈已经空了!");
			return;
		}
		while (true) {
			if (temp.next.next == null) { // 已经遍历到链表的最后;
				break;
			}
			temp = temp.next;
		}
		System.out.println(temp.next + "已出栈");
		temp.next = null;
	}
	//遍历栈
	public void show() {
		Liststack temp = head.next;
		if (temp == null) {
			System.out.println("栈已经空了!");
			return;
		}
		while (true) {
			if (temp == null) {
				break;
			}
			System.out.println(temp);
			temp = temp.next;
		}
	}
}

测试代码

public class Liststacktext {

	public static void main(String[] args) {
		Liststack l1=new Liststack(1);
		Liststack l2=new Liststack(2);
		Liststack l3=new Liststack(3);
		Liststack l4=new Liststack(4);
	 //Liststack l5=new Liststack(5);
		Stack1 lis=new Stack1(4);
		lis.add(l1);
		lis.add(l2);
		lis.add(l3);
		lis.add(l4);
		
//		lis.pop();
//		lis.pop();
//		lis.pop();
		lis.pop();
		lis.show();

	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值