Reverse Linked List II [LeetCode]

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.

Summary: First writes down the reverse parts (m to n) , then handles nodes before the m-th node and after the n-th node.

 1 class Solution {

 2 public:

 3     ListNode *reverseBetween(ListNode *head, int m, int n) {

 4         ListNode * current = head;

 5         ListNode * pre_m_node = NULL;

 6         ListNode * new_head = NULL;

 7         int i = 0;

 8         while(current != NULL) {

 9             if(i == m -1)

10                 break;

11             pre_m_node = current;

12             i ++;

13             current = current -> next;

14         }

15         //reverse m to n

16         ListNode * pre_n_node = current; 

17         int num_of_reverse_op = 0;

18         int num_of_nodes_to_reverse = n - m + 1;

19         while(num_of_reverse_op < num_of_nodes_to_reverse) {

20             ListNode * pre_head = new_head;

21             new_head = current;

22             current = current -> next;

23             num_of_reverse_op ++;

24             new_head -> next = pre_head;

25         }

26         //connect rest node after the nth node

27         pre_n_node -> next = current;

28         

29         if(pre_m_node != NULL) {

30             pre_m_node -> next = new_head;

31             return head;

32         } else {

33             return new_head;

34         }

35     }

36 };

 

你可能感兴趣的:(LeetCode)