
难度:Medium
解题思路:
先找到中间节点,将链表截断。
1->2->3->4->5 after cut: 1->2->3 4->5
1->2->3->4 after cut: 1->2 4->5
将后面的链表翻转。
1->2->3 5->4
1->2 4->5
将两个链表merge。
1->5->2->4->3
1->4->2->5
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
/** * 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) return ; ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *slow = dummy; ListNode *fast = dummy; while(fast -> next != NULL && fast -> next -> next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode *another_head = NULL; if(fast ->next != NULL) { another_head = slow->next->next; slow->next->next = NULL; } else { another_head = slow->next; slow->next = NULL; } ListNode *another_pre = NULL; ListNode *another_cur = another_head; while(another_cur != NULL) { // cout<<"value:"<<another_cur->val<<endl; ListNode *another_next = another_cur->next; another_cur->next = another_pre; another_pre = another_cur; another_cur = another_next; } another_head = another_pre; another_cur = another_head; // if(another_cur != NULL) // { // another_head = another_cur; // } // else // { // cout<<"error"<<endl; // } ListNode *cur = dummy->next; while(cur != NULL && another_cur != NULL) { ListNode *cur_next = cur->next; ListNode *another_cur_next = another_cur->next; cur->next = another_cur; another_cur->next = cur_next; cur = cur_next; another_cur = another_cur_next; } } };
|
运行结果:49ms,超过73.25%
近期评论