Java easy understand sol.


  • 0
    J

    This is an easy understand sol. Just use brute-force approach, not neat but easy for people who have difficult in solving this one firstly.

    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode node_m_pre = null;
    		ListNode node_m = null;
    		ListNode node_n = null;
    		ListNode node_n_next = null;
    		ListNode dummy = new ListNode(0);
    		dummy.next = head;
    		ListNode cur = dummy;
    		for(int i=0;;i++){
    			if(i==m-1){
    				node_m_pre = cur;
    				node_m = cur.next;
    			}
    			if(i==n){
    				node_n = cur;
    				node_n_next = cur.next;
    			}
    			if(cur.next==null) break;
    			cur = cur.next;
    		}
    		node_n.next = null;
    		node_m_pre.next = reverse(node_m);
    		node_m.next = node_n_next;
    		head = dummy.next;
    		return head;
        }
        
        public ListNode reverse(ListNode head){
    		ListNode pre = null;
    		ListNode cur = head;
    		while(cur != null){
    			ListNode next = cur.next;
    			cur.next = pre;
    			pre = cur;
    			cur = next;
    		}
    		return pre;
    	}
    }

Log in to reply
 

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