栈和队列:
1、设计一个有getMin功能的栈
题目:
实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
要求:
1、pop、push、getMin操作的时间复杂度都是O(1)
2、设计的栈类型可以输用现成的栈结构
package 设计一个有getMin功能的栈;
import java.util.Stack;
public class MyStack1 {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack1()
{
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int newNum)
{
if(this.stackMin.isEmpty())
{
this.stackMin.push(newNum);
}
else if(newNum <= this.getmin())
{
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int pop()
{
if(this.stackData.isEmpty())
{
throw new RuntimeException("Your stack is Empty.");
}
int value = this.stackData.pop();
if(value == this.getmin())
{
this.stackMin.pop();
}
return value;
}
public int getmin()
{
if(this.stackMin.isEmpty())
{
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();
}
}
由两个栈组成的队列
题目:
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)
package 由两个栈组成的队列;
import java.util.Stack;
public class TwoStackQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStackQueue()
{
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void add(int pushInt)
{
stackPush.push(pushInt);
}
public int poll()
{
if(stackPop.empty() && stackPush.empty())
{
throw new RuntimeException("Queue is empty!");
}
else if(stackPop.empty())
{
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek()
{
if(stackPop.empty() && stackPush.empty())
{
throw new RuntimeException("Queue is empty!");
}
else if(stackPop.empty())
{
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}
3、如何仅用递归函数和栈操作逆序一个栈
题目:
一个栈一次压入1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1,将这个栈转置后,从栈顶到栈底为1、2、3、4、5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构.
第二章
1、给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
package 打印两个有序链表的公共部分;
public class Node {
public int value;
public Node next;
public Node(int data)
{
this.value = data;
}
public void printCommonPart(Node head1,Node head2)
{
System.out.println("Common Part: ");
while (head1 != null && head2 != null) {
if(head1.value < head2.value)
{
head1 = head1.next;
}
else if(head1.value > head2.value)
{
head2 = head2.next;
}
else {
System.out.println(head1.value + " ");
head1 = head1.next;
head2 = head2.next;
}
}
System.out.println();
}
}