leetcode143. Reorder List
2018-09-28 17:16 legend聪 阅读(217) 评论(0) 编辑 收藏 举报用快慢双指针,可以使慢指针到达中间的时候快指针到达最后一个元素(奇数),或者倒数第二个元素(偶数)。慢指针后面的元素是后半个链表,把后半个链表进行reverse,然后再插在原来的链表中就可以了
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { ListNode* reverse(ListNode* head) { ListNode* pre; ListNode* cur; cur = head; pre = NULL; while (cur!= NULL) { ListNode* next; next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } public: void reorderList(ListNode* head) { if (head==NULL||head->next == NULL || head->next->next == NULL) return; ListNode* fast; ListNode* slow; fast = head; slow = head; while (fast->next&&fast->next->next)//出来之后slow的下一个就是后半段. { fast = fast->next->next; slow = slow->next; } ListNode*q; q = reverse(slow->next); slow->next = NULL; ListNode*p; p = head; while (p&&q) { ListNode* temp; temp = new ListNode(q->val); temp->next=p->next; p->next = temp; p = temp->next; q = q->next; } return; } };