Leetcode 92. Reverse Linked List II

92. Reverse Linked List II

    My Submissions
Question Editorial Solution
Total Accepted: 69858  Total Submissions: 251099  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Linked List
Hide Similar Problems
  (E) Reverse Linked List


和链表反转的题很类似,不过这道题指定了反转的区间,而不是全部反转。

所以我们将链表划分为三个子区间,在区间连接处连接即可。


上代码:

ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(head == NULL || head->next == NULL) return head;
        
    	ListNode *q = NULL, *p = head;
    	for (int i = 0; i < m - 1; i++)
    	{
    		q = p;
    		p = p->next;
    	}
    
    	// p此时指向第m个结点
    	ListNode *end = p;
    	ListNode *pPre = p, *nxt = NULL;
    	p = p->next;
    
    	// m->n之间的结点逆序
    	for (int i = m + 1; i <= n; ++i)
    	{
    		nxt = p->next;
    		p->next = pPre;
    		pPre = p;
    		p = nxt;
    	}
        // p指向原链表中第n个结点的下一个结点
        // end表示逆序子链表的尾结点
    	end->next = p;
        
        // pPre指向的是逆序后的子链表头
        // q指向的是第m个结点前一个结点 注意有可能是NULL
    	if (q)
    		q->next = pPre;	// 不是NULL 链接起来即可
    	else
    		head = pPre;	// 是NULL 头结点即为子链表头
    
    	return head;
    }


你可能感兴趣的:(LeetCode,——,链表系列)