import java.util.Scanner;
public class Hello {
public static void main(String[] args){
Stack S=new Stack();
Scanner reader=new Scanner(System.in);
System.out.println("请输入数据,最后按233结束");
int data=reader.nextInt();
while(data!=233) {
S.Push(data);
data=reader.nextInt();
}
System.out.print("栈内元素为:");
S.show();
boolean flag=true;
while(flag) {
System.out.println("请输入你的操作:1、进栈 2、出栈 3、查看 4、结束 ");
int choose=reader.nextInt();
switch(choose)
{
case 1: System.out.println("请输入进栈数值");
data=reader.nextInt();
S.Push(data);
System.out.print("栈内元素为:");
S.show();
break;
case 2: S.Pop();
System.out.print("栈内元素为:");
S.show();
break;
case 3: System.out.print("栈内元素为:");
S.show();
break;
case 4: flag=false; break;
default: break;
}
}
reader.close();
}
}
class Node{
int data;
Node next;
Node(int data){
this.data=data;
next=null;
}
}
class Stack{
int length=0; //栈内元素个数
Node top;
///
// 进栈
///
void Push(int data){
Node newnode=new Node(data);
length++;
if(length==1) {
top=newnode;
}
else {
newnode.next=top;
top=newnode;
}
}
///
// 出栈
///
int Pop() {
if(length<=0) {
System.out.println("栈空");
return 0;
}
Node cur=top;
if(length==1) {
top=null;
length--;
return 0;
}
else{
top=top.next;
cur.next=null;
length--;
return 0;
}
}
///
// 取栈顶元素
//
int GetTop() {
int data;
data=top.data;
return data;
}
///
// 查看
//
void show() {
Node cur=top;
while(cur!=null) {
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.print("链栈长度为:"+length);
System.out.println();
}
}
JAVA 链栈
最新推荐文章于 2023-05-04 20:55:05 发布