Simple Java using Stack


  • 0
    S
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode tmp1=null,cur1=head,prev1=null;
            Stack<Integer> st = new Stack();
            int count=1;
            while(cur1!=null){
                if(count>=m && count<=n){
                    st.push(cur1.val);
                }
                count++;
                cur1 = cur1.next;
            }
            cur1=head;
            count=1;
            while(cur1!=null){
                if(count>=m && count<=n){
                if(!st.isEmpty()) cur1.val=st.pop();
                }
                count++;
                cur1=cur1.next;
            }
            return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.