设计getMin功能的栈

题目描述

实现一个特殊功能的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。

输入描述:

第一行输入一个整数N,表示对栈进行的操作总数。

下面N行每行输入一个字符串S,表示操作的种类。

如果S为"push",则后面还有一个整数X表示向栈里压入整数X。

如果S为"pop",则表示弹出栈顶操作。

如果S为"getMin",则表示询问当前栈中的最小元素是多少。

输出描述:

对于每个getMin操作,输出一行表示当前栈中的最小元素是多少。
示例1

输入

复制
6
push 3
push 2
push 1
getMin
pop
getMin

输出

复制
1
2

备注:

1<=N<=1000000

-1000000<=X<=1000000

数据保证没有不合法的操作

代码实现:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

public class Main { static LinkedList<Node> stack=new LinkedList<Node>(); static Head head=new Head(); public static void push(int val){ Node node =new Node(val); stack.addFirst(node); //第一个元素 if (head.first == null){ head.first = node; head.last=node; return; } //插入到头 if (head.first.val >= val) { node.after=head.first; head.first.before=node; head.first=node; return; } //插入到尾部 if (head.last.val <= val){ head.last.after=node; node.before=head.last; head.last=node; return; } //在中间插入 Node next=head.first; while (next!=null){ if (next.val >= val){ node.after=next; node.before=next.before; next.before.after=node; next.before=node; return; } next=next.after; } } public static void pop(){ Node node = stack.removeFirst(); //移除前面那个元素 if (node.before == null){ if (node.after!=null){ node.after.before=null; } head.first=node.after; } if (node.after == null){ if (node.before !=null){ node.before.after=null; } head.last=node.before; } if (node.after!=null && node.before!=null){ node .before.after=node.after; node.after.before=node.before; } } public static void getMin(){ System.out.println(head.first.val); } public static void main(String[] args) throws IOException { BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in)); int row = Integer.valueOf(scanner.readLine()); for (int i = 0; i < row; i++) { String[] data = scanner.readLine().split(" "); if(data[0].equals("push")) { push(Integer.valueOf(data[1])); continue; } if (data[0].equals("pop")) { pop(); continue; } getMin(); } scanner.close(); } } class Head{ Node first; Node last; } class Node{ Node before; int val; Node after; public Node(int val) { this.val = val; } } 

简单说明下:

push操作

pop操作也类似,这里就不说了。

运行结果

来源:http://daohang.1994july.club/

猜你喜欢

转载自www.cnblogs.com/1994july/p/12403523.html