码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Reverse Linked List II

时间:2016-04-05 07:08:50      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Reverse a linked list from position m to n.

 

Notice

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

Example

Given 1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL.

Challenge

Reverse it in-place and in one-pass

 

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list 
     * @oaram m and n
     * @return: The head of the reversed ListNode
     */
    public ListNode reverseBetween(ListNode head, int m , int n) {
        // write your code
        
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        ListNode end1 = fakehead;
        
        for(int i = 1; i < m; i++)
            end1 = end1.next;
        
        ListNode head2 = end1.next;
        end1.next = null;
        
        ListNode end2 = head2;
        
        for(int i = 0; i < n - m; i++)
            end2 = end2.next;
        
        ListNode head3 = end2.next;
        end2.next = null;
        head2 = reverse(head2);
        
        end1.next = head2;
        end2 = head2;
        while(end2.next != null)
            end2 = end2.next;
        end2.next = head3;
        
        return fakehead.next;
    }
    
        public ListNode reverse(ListNode head){
        if(head == null || head.next == null)
            return head;
        
        ListNode prev = head;
        ListNode curr = head.next;
        ListNode next = head.next.next;
        
        head.next = null;
        
        while(next != null){
            curr.next = prev;
            prev = curr;
            curr = next;
            next = next.next;
        }
        
        curr.next = prev;
        
        return curr;
    }
}

 

lintcode-medium-Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5353639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!