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

链表内指定区间反转

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

利用栈stack把链表数据置换

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
public class Solution {
    /**
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        Stack stack = new Stack();
        ListNode temp = null;
        ListNode p = head;
        int size = 0;
        while (head != null) {
            size++;
            if (size >= m && size <= n) {
                stack.push(head.val);      
            }
            head = head.next;
        }
        head = p;
        size = 0;
        while (head != null) {
            size++;
            if (size >= m && size <= n) {
                head.val = stack.pop();
            }
            head = head.next;
        }
        return p;
    }
}
全部评论
很好很明了😍
点赞 回复 分享
发布于 2023-03-14 00:11 青海

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务