143. 重排链表
思路:找到中点断开,翻转后面部分,然后合并前后两个链表
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: void reorderList(ListNode* head) { ListNode *middle, *tail, *right, *left, *t1, *t2; if(head && head->next) { middle = Find_middle(head); tail = middle->next; middle->next = NULL; right = Reorder(tail); left = head; while(left&&right) { t1 = left->next;//t1 = 2 t1 = 3 t2 = right->next;//t2 = 4 t2 = null left->next = right;//1->5 2->4 left = t1;//left = 2 left = 3 right->next = left;//5->2 4->3 right = t2;//right = 4 right = null } } } ListNode *Find_middle(ListNode *head) { ListNode *fast, *slow; fast = head->next; slow = head; while(fast&&fast->next) { fast = fast->next->next; slow = slow->next; } return slow; } ListNode *Reorder(ListNode *head) { //1->2->3->4->5 ListNode *current, *pre, *temp; if(head == NULL||head->next==NULL) return head; current = head;//current = 1 pre = current->next;//pre = 2 current->next = NULL;//1->null while(pre) { temp = pre->next; //temp = 4 temp = 5 temp = null pre->next = current;// 3->2 4->3 5->4 current = pre;//current = 3 current = 4 current = 5 pre = temp;//pre = 4 pre = 5 pre = null } return current; } };
原文:https://www.cnblogs.com/jessica216/p/13394329.html