算法(二十四)
1、给出两个分别有序的单链表,将其合并成一条新的有序单链表。
举例:1→3→5和2→4→6合并之后为1→2→3→4→5→6
public static Node mergeList(Node list1, Node list2){
if(list1==null) return list2;
if(list2 == null) return list1;
Node resultNode;
if(llist1.val < list2.val){
resultNode = list1;
list1 = list1.next;
}else{
resultNode = list2;
list2 = list2.next;
}
resultNode.next = mergeList(list1, list2);
return resultNode;
}
2、定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。在该栈中,调用min、push和pop方法,且各个函数的时间复杂度均为O(1)。
import java.util.Stack;
public class Main{
Stack<Integer> stack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int node){
stack.push(node);
if(minStack.isEmpty() || minStack.peek()>= node){
minStack.push(node);
}
}
public void pop(){
if(stack.peek() == minStack.peek()) minStack.pop();
stack.pop();
}
public int top(){
return stack.peek();
}
pubic int min(){
if(stack.peek() == minStack.peek()){
return minStack.peek();
}
}
}
根据自己所见所闻进行算法归纳总结