剑指offer30:包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
解题思路:
借助一个辅助栈B,将栈A中的元素取出把较大值放入栈B中直至A为空,栈B的栈顶元素就是最小值。
class MinStack {
Stack<Integer> A,B;
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.add(x);
if(B.empty() || B.peek() >= x)
B.add(x);
}
public void pop() {
if(A.pop().equals(B.peek()))
B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}
剑指offer6:从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
解题思路:
借助栈先入后出的特点,将链表元素压入栈再弹出就是倒序
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while(temp != null){
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for(int i = 0;i < size;i++){
print[i] = stack.pop().val;
}
return print;
}
}
剑指offer24:反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解题思路:
简答粗暴,把当前节点的next指向当前节点的prve。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}