1、题目描述
2、题目分析
首先将链表分为两段,然后将后面的一段反转,再合并两个链表。
3、代码
1 void reorderList(ListNode* head) { 2 if (head == nullptr || head->next == nullptr || head->next->next == nullptr) 3 return ; 4 5 ListNode *newH = splitList(head); 6 ListNode *rp = reverseList(newH); 7 mergeList(head, rp); 8 } 9 10 11 ListNode *reverseList(ListNode* list) 12 { 13 if (list == NULL || list->next == NULL) 14 return list; 15 16 ListNode *p = list; 17 ListNode *pn = list->next; 18 list->next = NULL; 19 20 while (pn != NULL) { 21 ListNode *tmp = pn->next; 22 pn->next = p; 23 p = pn; 24 pn = tmp; 25 } 26 return p; 27 } 28 29 void mergeList(ListNode *head_1, ListNode *head_2) 30 { 31 ListNode *p; 32 ListNode *pm = head_1; 33 ListNode *pn = head_2; 34 while (pm != NULL && pn != NULL) { 35 ListNode *tmpm = pm->next; 36 ListNode *tmpn = pn->next; 37 pm->next = pn; 38 if (tmpm != NULL) 39 pn->next = tmpm; 40 pm = tmpm; 41 pn = tmpn; 42 } 43 } 44 45 ListNode *splitList(ListNode *head) 46 { 47 if (head == NULL || head->next == NULL) 48 return head; 49 ListNode *pm = head; 50 ListNode *pn = head; 51 52 while (pn != NULL && pn->next != NULL) { 53 pm = pm->next; 54 pn = pn->next->next; 55 56 } 57 58 ListNode *newH = NULL; 59 if (pn == NULL) { 60 newH = pm; 61 ListNode *pt = head; 62 while (pt->next != newH) { 63 pt = pt->next; 64 } 65 pt->next = NULL; 66 } else if (pn->next == NULL) { 67 newH = pm->next; 68 pm->next = NULL; 69 } 70 71 72 return newH; 73 }