java中推荐使用Deque(双端队列)来代替stack。这里给出初始化一个Deque的方法以及对应栈和单端队列的方法
ArrayDeque<String> stack = new ArrayDeque<>();
使用两个栈实现队列功能,代码较为简单。重点要熟悉Deque的方法。
class MyQueue {
ArrayDeque<Integer> stackin;
ArrayDeque<Integer> stackout;
public MyQueue() {
stackin =new ArrayDeque<>();//负责入栈
stackout =new ArrayDeque<>();//负责出栈
}
public void push(int x) {
stackin.addFirst(x);
}
public int pop() {
stackmoveout();
int x=stackout.removeFirst();
stackmovein();
return x;
}
public int peek() {
stackmoveout();
int x=stackout.removeFirst();
stackout.addFirst(x);
stackmovein();
return x;
}
public boolean empty() {
if(stackin.isEmpty()&&stackout.isEmpty()){
return true;
}else{
return false;
}
}
public void stackmoveout(){
while(!stackin.isEmpty()){
stackout.addFirst(stackin.removeFirst());
}
}
public void stackmovein(){
while(!stackout.isEmpty()){
stackin.addFirst(stackout.removeFirst());
}
}
}
这里使用一个队列即可实现栈
class MyStack {
ArrayDeque<Integer> queue;
public MyStack() {
queue=new ArrayDeque<>();
}
public void push(int x) {
queue.addLast(x);
}
public int pop() {
for(int i=0;i<queue.size()-1;i++){
queue.addLast(queue.removeFirst());
}
int x=queue.removeFirst();
return x;
}
public int top() {
for(int i=0;i<queue.size()-1;i++){
queue.addLast(queue.removeFirst());
}
int x=queue.removeFirst();
queue.addLast(x);
return x;
}
public boolean empty() {
if(queue.isEmpty()){
return true;
}else{
return false;
}
}
}
链表相关题目一定要记得虚拟头结点法。这里利用之前反转链表的方法,但是要分段,每一段的头结点最后是要指向第二段的头结点。这里直接设计一个反转函数,传入指针cur和k作为参数,反转cur后的k个节点。使用root节点指向cur,在对root节点后的k个节点进行反转时,要使用cur进行遍历,判断root节点后是否还有k个节点。这里直接引用大神的图。
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummyhead=new ListNode(-1,head);
ListNode root=dummyhead;
ListNode cur=dummyhead;
while(cur!=null){
reverse(cur,k);
int x=k;
while(x>0&&cur!=null){
cur=cur.next;
x--;
}
}
return dummyhead.next;
}
public void reverse(ListNode root,int k){
int u=k;
ListNode cur=root;
while(u>0&&cur!=null){ //判断是否还有k个节点
cur=cur.next;
u--;
}
if(cur==null){
return;
}
ListNode tail=cur.next;
ListNode a=root.next;
ListNode b=a.next;
while(k>1){
ListNode c=b.next;
b.next=a;
a=b;
b=c;
k--;
}
root.next.next=tail;
root.next=a;
}
}