用链表来实现堆栈

数组结构实现堆栈较为简单,但因为如果堆栈本身是变动的话,数组大小并无法实现规划声明,因此,使用链表来实现堆栈可以随时改变链表的长度,不过缺点是设计算法较为复杂。

package Stack;

public class StackBylink {
	public Node front;//指向堆栈底部的指针
	public Node rear;//指向堆栈顶端的指针
	public boolean isEmpty() {//类方法:判断堆栈是否为空堆栈
		return front==null;
	}
	public void out_of_Stack() {//类方法:打印输出堆栈中的内容
		Node current=front;//定义指向底部的指针
		while(current!=null) {//输出堆栈中的内容
			System.out.print("["+current.data+"]");
			current=current.next;
		}
		System.out.println();
	}
	public void insert(int data) {//类方法:把指定的数据压入堆栈的顶端
		Node newNode=new Node(data);//创建一个名为newNode的对象
		if(this.isEmpty()) {//判断链表是否为空
			front=newNode;
			rear=newNode;
		}else {				//将数据压入堆栈
			rear.next=newNode;
			rear=newNode;
		}
	}
	public void pop() {//类方法:从堆栈顶端弹出数据
		Node newNode;//
		if(this.isEmpty()) {
			System.out.println("当前为空堆栈");
			return;
		}
		newNode=front;
		if(newNode==rear) {
			front=null;
			rear=null;
			System.out.println("当前为空堆栈");
		}else {
			while(newNode.next!=rear)
				newNode=newNode.next;
			
				newNode.next=rear.next;
				rear=newNode;
			
		}
		
	}
	
}
package Stack;
import java.io.*;
public class Linktest {
	public static void main(String args[]) throws IOException{
		BufferedReader buf;
		buf=new BufferedReader(new InputStreamReader(System.in));
		StackBylink stack_by_linkedlist=new StackBylink();
		int choice=0;
		while(true) {
			System.out.println("(0)结束(1)将数据压入堆栈(2)从堆栈弹出数据:");
			choice=Integer.parseInt(buf.readLine());
			if(choice==2) {
				stack_by_linkedlist.pop();
				System.out.println("数据弹出后堆栈的内容:");
				stack_by_linkedlist.out_of_Stack();
			}else if(choice==1) {
				System.out.println("请输入要压入堆栈的数据:");
				choice=Integer.parseInt(buf.readLine());
				stack_by_linkedlist.insert(choice);
				System.out.println("数据压入后堆栈中的内容:");
				stack_by_linkedlist.out_of_Stack();
			}else if(choice==0) {
				break;
			}else {
				System.out.println("输入错误!");
			}
		}
		
		
	}
	
	
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值