从尾到头打印链表
描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
思路:
输入正向输出反向符合栈的特性
(1)定义一个栈保存节点,循环把所有节点入栈
(2)定义一个数组,长度就是栈长,依次把栈顶元素放进数组就好了
(3)返回数组
代码:
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> s = new Stack<>();
ListNode cur = head;
while(cur != null){
s.push(cur);
cur = cur.next;
}
int size = s.size();
int[] arr = new int[size];
for(int i = 0; i < size; i++){
arr[i] = s.pop().val;
}
return arr;
}
}
左旋转字符串
描述:
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
思路:
使用切片直接返回
或者拼接字符串
(1)初始化一个辅助字符串res为空字符串
(2)循环从n到字符串尾取字符和res连接运算
(3)循环从0到n取字符和res连接运算
代码:
class Solution {
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i = n; i < s.length(); i++){
res += s.charAt(i);
}
for(int i = 0; i < n; i++){
res += s.charAt(i);
}
return res;
}
}
包含min函数的栈
描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
思路:
使用辅助栈记录最小值
(1)定义两个Stack
(2)入栈的时候给s1直接入栈
对于s2,判断若s2为空或者x小于s2的栈顶元素,代表此时x最小,入栈否则把s2栈顶重新入栈(出栈后栈顶还是最小值)
代码:
class MinStack {
Stack<Integer> s1;
Stack<Integer> s2;
/** initialize your data structure here. */
public MinStack() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
if(s2.isEmpty() || s2.peek() > x){
s2.push(x);
}else{
s2.push(s2.peek());
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}