LeetCode Reverse Linked List II

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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值