当前位置: 代码迷 >> 综合 >> leetcode练习题 recorder-list
  详细解决方案

leetcode练习题 recorder-list

热度:32   发布时间:2023-12-15 10:06:05.0

思路

快慢指针找到链表的中间结点,将原链表分为两部分,之后将链表的后半部分逆置,之后合并两个单链表,注意:一定要判定头部是否为空!

代码

class Solution {
public:void reorderList(ListNode *head) {if (head != NULL){//快慢指针求中间结点ListNode *slow = head;ListNode *fast = head;while (fast->next != NULL && fast->next->next != NULL){slow = slow->next;fast = fast->next->next;}//将链表的后面部分逆置fast = slow->next;slow->next = NULL;ListNode *new_head = new ListNode(0);while (fast){ListNode *tmp = fast->next;fast->next = new_head->next;new_head->next = fast;fast = tmp;}//合并ListNode *p = head;ListNode *q = new_head->next;while (q != NULL){ListNode *n = q->next;q->next = p->next;p->next = q;p = p->next->next;q = n;}}}
};
  相关解决方案