leetcode 92. 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.



class Solution {
 public:
	 ListNode* reverseBetween(ListNode* head, int m, int n) {
		 if (n - m < 1)
			 return head;
		 ListNode*p = head,*pre=NULL;
		 int k = 1;
		 while (k < m)
		 {
			 pre = p;
			 p = p->next; k++;
		 }
		 ListNode*hea = p,*p1=p->next;
		 while (k < n)
		 {
			 ListNode*nxt = p1->next;
			 p1->next = hea;
			 hea = p1;
			 p1 = nxt;
			 k++;
		 }
		 if (pre == NULL)
			 head = hea;
		 else
			 pre->next = hea;
		 p->next = p1;
		 return head;
	 }
 };

accepted

你可能感兴趣的:(LeetCode)