-
获取链表遍历题
解答:链表是一个个节点连接起来形成一个链,所有遍历只能从头开始往后遍历。
public class Solution {public ListNode findKthTotail(ListNode head, int k) { List nodeList = new ArrayList<>(); while (head != null) { nodeList.add(head); head = head.next; } return nodeList.get(nodeList.size() - k); } }
-
两个栈变为一个队列
解答:栈是先进后出,队列是先进先出
public class Solution {Stack stack1 = new Stack<>(); Stack stack2 = new Stack<>();
/**
- 新增元素
- @param node */ public void push(int node) { stack1.push(node); }
/**
- 获取元素
- @return */ public int pop() { //将stack1取出放到,stack2 while (!stack1.empty()) { Integer pop = stack1.pop(); stack2.push(pop); } //取出stack2最上面元素 int resInt = stack2.pop(); //再将stack2剩余元素放到stack1 while (!stack2.empty()) { Integer pop2 = stack2.pop(); stack1.push(pop2); } return resInt; } }