【LeetCode】92. Reverse Linked List II

Problem:

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

题目:逆转m到n位节点顺序,其余部分不变。一次遍历完成。


思路:想哭,明明知道大致思路,但是操作不熟练,总是造成某个案例不能测通。

1.遍历链表,count计数节点数。当遇到m-1时,pre指向m位前一个节点,temp指向遍历的当前节点cur的前一位。post指向cur后一位节点。

2.当count计数在m和n之间时,即(m,n],操作cur指向temp。再temp向后移动一个节点。即temp=cur;

3.当count小于n时,cur和post继续后移;即cur=post;post=post.next;当count等于n时,跳出循环;否则循环2.3步骤;

4.将m位节点next指向post,即指向后半部分,m-1位指向cur(此时cur在第n位),即pre.next=cur;

完成操作    


代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null||head.next==null)
            return head;
        if(m==n)
        	return head;
        ListNode node = new ListNode(0);
        node.next=head;
        ListNode pre = node;
        ListNode post = head.next;
        ListNode cur=head;
        ListNode temp=pre.next;
        int count=1;
        while(post!=null) {
        	if(count==m-1) {
        		pre=cur;
        		temp=pre.next;
        	}
        	if(count>m&&count<=n) {
        		cur.next=temp;
        		temp=cur;
        	}
        	if(count<n) {
        		cur=post;
        		post=post.next;
        	}
        	if(count>=n)
        		break;
        	count++;
        }
        //在n为末位节点时,while循环将会少比非末位节点少循环一次,提前判空结束,从而cur.next没有指到temp上。
        //会操作链表断链。
        if(post==null)
        	cur.next=temp;
        	
        pre.next.next=post;
        pre.next=cur;
        
        return node.next;
    }
}
     注: 在n为末位节点时,while循环将会少比非末位节点少循环一次,提前判空结束,从而cur.next没有指到temp上。会操作链表断链。

猜你喜欢

转载自blog.csdn.net/hc1017/article/details/80197223