超时,思路感觉很好,每次反转,
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode* head) { int index=1; ListNode* tem=head; while(tem) { if(index++ %2 == 1) { tem->next=reverseList(tem->next); } else tem=tem->next; } } ListNode* reverseList(ListNode* head) { if (head == NULL) return head; ListNode* H = head; head = head->next; H->next = NULL; while (head) { ListNode* next = head->next; head->next = H; H = head; head = next; } return H; } };
还有一个思路是:从中间断开,找到后一半的链表,反转后一半链表,依次插入
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode* head) { if(head == NULL || head->next==NULL || head->next->next==NULL) return ; ListNode* slow=head,*fast=head; while(fast) { slow=slow->next; fast=fast->next->next; if(fast->next==NULL || fast->next->next==NULL) break; } ListNode* second=(slow->next); slow->next=NULL; second=reverseList(second); ListNode* tem=head; while(second) { ListNode* sec_t=second->next; second->next=tem->next;; tem->next=second; tem=tem->next->next; second=sec_t; } } ListNode* reverseList(ListNode* head) { if (head == NULL) return head; ListNode* H = head; head = head->next; H->next = NULL; while (head) { ListNode* next = head->next; head->next = H; H = head; head = next; } return H; } };