用两个栈实现队列&&跳台阶&&链表中的节点每k个一组旋转

144 阅读1分钟

NC76 用两个栈实现队列

题目链接

1、解题思路
  • 模拟一下就好了
2、代码
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack2.push(node);
    }
    
    public int pop() {
        if(stack1.isEmpty()){
            while(!stack2.isEmpty()){
                stack1.push(stack2.pop());
            }
            return stack1.pop();
        }else{
            return stack1.pop();
        }
    }
}

NC68 跳台阶

题目链接

1、解题思路
  • 斐波那契数列
2、代码
public class Solution {
    public int jumpFloor(int n) {
        if(n <= 1){
            return n;
        }else{
            int a = 1,b = 2;
            for(int i = 3;i <= n;i++){
                int c = b;
                b = a + b;
                a = c;
            }
            return b;
        }
    }
}

NC50 链表中的节点每k个一组旋转

题目链接

1、解题思路
  • 针对组内,按照头插法实现逆转;针对组间,实现尾插
2、代码
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */

    private int getLength(ListNode node){
        int ans = 0;
        ListNode temp = node;
        while(temp != null){
            ans++;
            temp = temp.next;
        }
        return ans;
    }
    
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        int len = getLength(head);
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        int time = len / k;
        int index = 0;
        ListNode temp = head;
        while(index < time){
            ListNode node = new ListNode(0);
            for(int i = 0;i < k;i++){
                ListNode n = new ListNode(temp.val);
                n.next = node.next;
                node.next = n;
                temp = temp.next;
            }
            tail.next = node.next;
            while(tail.next != null){
                tail = tail.next;
            }
            index++;
        }
        tail.next = temp;
        return dummy.next;
    }
}