143. 重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3. 示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
做法是单双指针,来找到中间位置,值得注意的是如果是 (1)1 2 3 4 5 6 最后指向的分别为3和6 (2)1 2 3 4 5 最后指向的分别为3和5 需要 reverse(p1->next); 另外(p->next->next && p->next)判断不然会空指针异常
/** * 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: ListNode* reverse(ListNode *head){ ListNode *new_head = new ListNode; new_head = NULL; while(head){ ListNode *next = head->next; head->next = new_head; new_head = head; head = next; } return new_head; } void reorderList(ListNode* head) { ListNode *p1 = head; ListNode *p2 = head; if(p1 == NULL){ return; } while(p2->next && p2->next->next){ p1 = p1->next; p2 = p2->next->next; } ListNode *head1 = head; ListNode *head2 = reverse(p1->next); p1->next = NULL; ListNode *temp1,*temp2; ListNode *f1,*f2; f1 = head1; f2 = head2; while(head1 && head2){ temp1 = head1->next; temp2 = head2->next; head2->next = head1->next; head1->next = head2; head1 = temp1; head2 = temp2; } head = f1; } };