题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        Stack<ListNode> st = new Stack<>();
        ListNode op = head, temp;
        if (m == 1) {
            for (int i = m - 1; i < n; i++) {
                st.add(op);
                op = op.next;
            }
            head=st.pop();
            temp=head;
            while(!st.isEmpty()){
                temp.next=st.pop();
                temp=temp.next;
            }
            temp.next=op;
        } else {
            for (int i = 0; i < m - 2; i++) {
                op = op.next;

                System.out.println(op.val);
            }
            for (int i = m - 1; i < n; i++) {
                temp = op.next;
                st.add(temp);
                op.next = temp.next;
            }
            temp = op.next;
            while (!st.isEmpty()) {
                op.next = st.pop();
                op = op.next;
            }
            op.next = temp;
        }

        // reverse(op,n-m);

        return head;
    }
}

就是使用了栈,将要转的直接放到栈里面,也不用太过思考临界值的问题。

不过由于代码能力不行,还是把m=1 的分开思考了。

全部评论

相关推荐

11-29 00:55
门头沟学院
区域赛银,邀请赛金,打算十二月打下Java基础、背点八股、写个外卖后去投福建小厂的寒假实习,简历应该怎么写呢?以及福州/和厦门有推荐的小厂吗?
牛客53210502...:简历一页:把区域银,邀请赛金标粗,其他的奖除非凑一页否则没有必要写。或者多页:每个站一行这样都列出来。项目经历看看牛客其他人是怎么写的,写的不好呢。简历打磨好按部就班没问题的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务