92. 反转链表 II

时间:2019-09-14
本文章向大家介绍92. 反转链表 II,主要包括92. 反转链表 II使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、直接迭代

 1 ListNode* reverseBetween(ListNode* head, int m, int n) {
 2     ListNode* start = head;
 3     ListNode* end = head;
 4 
 5     ListNode* start1 = head;
 6     ListNode* end1 = head;
 7     ListNode* temp = head;
 8     ListNode* next = head;
 9     ListNode* dummy = nullptr;
10     int m_temp = m;
11     while (--m_temp)
12     {
13         start = temp;
14         temp = temp->next;
15     }
16     start1 = temp;
17     
18     int num = n-m+1;
19     
20     while (num--)
21     {
22         next = temp->next;
23         temp->next = dummy;
24         dummy = temp;
25 
26         if (num == 0)
27             end1 = temp;
28         temp = next;
29     }
30     end = temp;
31     if (m == 1)
32     {
33         start->next = end;
34         return end1;
35     }
36     start->next = end1;
37     start1->next = end;
38 
39     return head;
40 }

二、递归交换数据域的值

 1 void recurseAndReverse(ListNode* &left,ListNode* right, int m, int n,bool & stop)
 2 {
 3     if (n == 1)
 4         return;
 5     right = right->next;
 6     if (m > 1)
 7         left = left->next;
 8     recurseAndReverse(left, right, m - 1, n - 1, stop);
 9 
10     if (left == right || right->next == left)
11         stop = true;
12     if (stop == false)
13     {
14         int temp = right->val;
15         right->val = left->val;
16         left->val = temp;
17 
18         left = left->next;
19     }
20 }
21 ListNode* reverseBetween(ListNode* head, int m, int n) {
22     bool stop = false;
23     ListNode* left = head;
24     ListNode* right = head;
25     recurseAndReverse(left,right, m, n,stop);
26 
27     return head;
28 }

压栈的过程:左边走到m就可以了,右边走到n就可以了。

右边走到就开始退栈:左边继续往后走,右边逐步往前走,相遇或者交错一步,在这个过程中交换数据域。

原文地址:https://www.cnblogs.com/zouma/p/11520039.html