学到了怎么找链表的中点。。快慢链表,下面这个没用快慢链表,是用的笨办法
1 void reorderList(ListNode* head) { 2 if (head == nullptr) 3 return; 4 ListNode* temp = head; 5 6 int count = 0; //找到mid部分 7 while (temp != nullptr) //快慢指针? 8 { 9 ++count; 10 temp = temp->next; 11 } 12 if (count % 2 == 1) 13 count+=1; 14 count /= 2; 15 16 temp = head; 17 ListNode* finish = nullptr; 18 while (count > 0) 19 { 20 --count; 21 if (count == 0) 22 finish = temp; 23 temp = temp->next; 24 } 25 finish->next = nullptr; //注意这个临界点,不处理会有循环出现 26 27 ListNode* behind = temp; 28 ListNode* front = head; 29 30 31 ListNode* reverse = nullptr; //翻转部分 32 temp = behind; 33 while (temp != nullptr) 34 { 35 temp = behind->next; 36 behind->next = reverse; 37 reverse = behind; 38 behind = temp; 39 } 40 behind = reverse; 41 42 ListNode* next = nullptr; 43 ListNode* next1 = nullptr; 44 while (behind != nullptr) 45 { 46 next = front->next; 47 next1 = behind->next; 48 49 front->next = behind; 50 behind->next = next; 51 52 front = next; 53 behind = next1; 54 } 55 }
下面这个是用了快慢链表的
1 void reorderList(ListNode* head) { 2 if (head == nullptr) 3 return; 4 ListNode* temp = head; 5 6 ListNode* fast = head; 7 ListNode* slow = head; 8 while (fast->next != nullptr&&fast->next->next != nullptr) 9 { 10 fast = fast->next->next; 11 slow = slow->next; 12 } 13 ListNode* behind = slow->next; 14 slow->next = nullptr; 15 ListNode* front = head; 16 17 ListNode* reverse = nullptr; //翻转部分 18 temp = behind; 19 while (temp != nullptr) 20 { 21 temp = behind->next; 22 behind->next = reverse; 23 reverse = behind; 24 behind = temp; 25 } 26 behind = reverse; 27 28 ListNode* next = nullptr; 29 ListNode* next1 = nullptr; 30 while (behind != nullptr) 31 { 32 next = front->next; 33 next1 = behind->next; 34 35 front->next = behind; 36 behind->next = next; 37 38 front = next; 39 behind = next1; 40 } 41 }
用了快慢链表来找中点,执行速度居然慢了。。所以time(遍历两遍链表)<time(两个结点一起走一遍链表)??