Leetcode 92. Reverse Linked List II

Posted zhangwj0101

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

Question

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

Code

 public ListNode reverseBetween(ListNode head, int m, int n) 

        ListNode p = head;
        ListNode result = new ListNode(0);
        result.next = p;
        ListNode pre = result;
        int len = 0;
        Stack<ListNode> stacks = new Stack<>();

        while (p != null) 
            len++;
            if (len < m) 
                pre = p;
             else if (len >= m && len <= n) 
                stacks.push(p);
             else if (len > n) 
                break;
            
            p = p.next;
        
        while (!stacks.isEmpty()) 
            ListNode node = stacks.pop();
            pre.next = node;
            pre = pre.next;
        
        pre.next = p;
        return result.next;
    

以上是关于Leetcode 92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode92]Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

Leetcode 92. Reverse Linked List II

leetcode.92. Reverse Linked List II

[LeetCode]92. Reverse Linked List II

LeetCode 92. Reverse Linked List II