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

LeetCode Reverse Linked List II

时间:2015-01-19 15:54:39      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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->NULLm = 2 and n = 4,

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

Note:
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.

思路分析:这题和LeetCode Reverse Nodes in k-Group很类似,要求对给定起始和结束位置的部分链表进行反转操作,我直接使用的LeetCode Reverse Nodes in k-Group里面的反转链表的函数AC的,需要注意传入正确的BeginNode和EndNode,同时对m和n取值的corner case要考虑周全。

AC Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null || head.next == null) return head;
        int i = 1;
        ListNode cur = head;
        ListNode beginNode = null;
        ListNode endNode = null;
        while(cur != null){
            if(i == m-1){
                beginNode = cur;
            }
            if(i == n+1){
                endNode = cur;
            }
            i++;
            cur = cur.next;
        }
        if(n == 1 || m == i-1) return head;
        if(m == 1){
            ListNode fakeNode = new ListNode(-1);
            fakeNode.next = head;
            beginNode = fakeNode;
        }
        ListNode firstInReverse = reverseLinkedList(beginNode, endNode);
        if(m == 1) return firstInReverse;
        else return head;
    }
    
    //reverse nodes between beginNode and endNode(exclusively)
	//return the first node in the reversed part
	private static ListNode reverseLinkedList(ListNode beginNode, ListNode endNode) {
		// TODO Auto-generated method stub
		ListNode head = beginNode.next;
		ListNode dummy = head;//use dummy to maintain the new head
		ListNode pre = head;
		ListNode cur = pre.next;
		ListNode after = cur.next;
		while(cur != endNode){
			pre.next = after;
			cur.next = dummy;
			dummy = cur;
			cur = pre.next;
			if(cur == null) break;
			after = cur.next;
		}
		beginNode.next = dummy;//!after reverse, beginNode should also before the first Node, endNode should also before the last node
		return dummy;
	}
}


LeetCode Reverse Linked List II

标签:

原文地址:http://blog.csdn.net/yangliuy/article/details/42873073

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