1丶合并两个有序链表
小菜坤的答案:
class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode newHead=new ListNode(0); ListNode tmp=newHead; while(list1!=null && list2!=null){ if(list1.val<list2.val){ tmp.next=list1; list1=list1.next; tmp=tmp.next; }else{ tmp.next=list2; list2=list2.next; tmp=tmp.next; } } if(list1!=null){ tmp.next=list1; } if(list2!=null){ tmp.next=list2; } return newHead.next; } }
2丶栈的压入、弹出序列
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pushV int整型一维数组 * @param popV int整型一维数组 * @return bool布尔型 */ public boolean IsPopOrder (int[] pushA, int[] popA) { if(pushA.length==0||popA.length==0){ return false; } Stack<Integer> stack=new Stack<>(); int j=0; for(int i=0;i<pushA.length;i++){ stack.push(pushA[i]); while (j<popA.length&&!stack.empty()&&stack.peek()==popA[j]){ stack.pop(); j++; } } return stack.empty(); } }
3丶设计循环队列
class MyCircularQueue { public int[] elem; public int front;//队头下标 public int rear;//队尾下标 public MyCircularQueue(int k) { this.elem=new int[k+1]; } //入队 public boolean enQueue(int value) { if(isFull()){ return false; } this.elem[rear]=value; rear=(rear+1) % elem.length; return true; } //出队 public boolean deQueue() { if (isEmpty()){ return false; } front=(front+1)%elem.length; return true; } //获取队头元素 public int Front() { if (isEmpty()){ return -1; } return elem[front]; } //获取队尾元素 public int Rear() { if (isEmpty()){ return -1; } int index=(rear==0)?elem.length-1:rear-1; return elem[index]; } public boolean isEmpty() { return rear==front; } public boolean isFull() { return (rear+1) % elem.length==front; } } /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue obj = new MyCircularQueue(k); * boolean param_1 = obj.enQueue(value); * boolean param_2 = obj.deQueue(); * int param_3 = obj.Front(); * int param_4 = obj.Rear(); * boolean param_5 = obj.isEmpty(); * boolean param_6 = obj.isFull(); */
4丶最小栈
import java.util.Stack; class MinStack { private Stack<Integer> s; //普通栈 private Stack<Integer> minStack;//维护当前栈的最小值 public MinStack() { s =new Stack<>(); minStack=new Stack<>(); } /* 入栈 */ public void push(int val) { s.push(val); if(minStack.empty()){ minStack.push(val); }else{ int peekV=minStack.peek(); if(val<=peekV){ minStack.push(val); } } } /* 出栈 */ public void pop() { if(!s.empty()){ int popV=s.pop(); int peekVMins=minStack.peek(); if(popV==peekVMins){ minStack.pop(); } } } /* 获取栈顶元素,但是不删除 */ public int top() { if(!s.empty()){ return s.peek(); } return -1; } //获取最小栈的栈顶元素 public int getMin() { if(!minStack.empty()){ return minStack.peek(); } return -1; } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(val); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */