堆栈链表实现——java

package Stack;
/**
 * 程序名称:CH04_03
 * 程序目的:链表制作堆栈
 * @author 86176
 *
 */
import java.io.*;
//链接节点的声明
class Node{
	int data;
	Node next;
	public Node(int data) {
		this.data=data;
		this.next=null;
	}
}

class StackByLink{
	public Node front;//指向堆栈底端的指针
	public Node rear;//指向堆栈顶端的指针
	//类方法:isEmpty()
	//判断堆栈如果为空栈,则front==null;
	public boolean isEmpty() {
		return front==null;
	}
	//类方法:output_of_Stack()
	//打印堆栈内容
	public void  output_of_Stack() {
		Node current=front;
		while(current!=null) {
			System.out.println("["+current.data+"]");
			current=current.next;
		}
		System.out.println();
	}
	//类方法:output_of_Stack()
	//在堆栈顶端加入数据
	public void insert(int data) {
		Node newNode=new Node(data);
		if(this.isEmpty()) {
			front=newNode;
			rear=newNode;
		}
		else {
			rear.next=newNode;
			rear=newNode;
		}
	}
	//类方法:output_of_Stack()
	//在堆栈顶端删除数据
	public void pop() {
		Node newNode;
		if(this.isEmpty())
		{
			System.out.print("==目前为空栈==");
			return;
		}
		newNode=front;
		if(newNode==rear) {
			front=null;
			rear=null;
			System.out.print("==目前为空栈==");
		}
		else {
			while(newNode.next!=rear)
				newNode=newNode.next;
			    newNode.next=rear.next;
			    rear=newNode;
		}
	}
}
public class CH04_03 {
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();
			stack_by_linkedlist.output_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.output_of_Stack();
		}
		else if(choice==0)
			break;
		else {
			System.out.println("输入错误!");
		}
	}
}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值