Leetcode学习笔记(143. 重排链表)

在这里插入图片描述
解法一:引入栈和队列的性质,缺点就是引入大量的额外空间;

/**
 * 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:
    void reorderList(ListNode* head) {
        ListNode* cur = head;
        queue<ListNode*> q_data;
        stack<ListNode*> s_data;
        int num = 0;
        while(cur!=nullptr){
            q_data.push(cur);
            s_data.push(cur);
            cur=cur->next;
            num++;
        }
        ListNode* out = new ListNode(0);
        cur = out;
        for(int i=0; i<(num+1)/2; i++) {
            ListNode* x = q_data.front();
            q_data.pop();
            ListNode* y = s_data.top();
            s_data.pop();
            if(x!=y){
                cur->next = x;
                x->next =y;
                y->next = nullptr;
                cur = y;
            }else{
                cur->next = x;
                x->next = nullptr;
            }
        }
        head = out->next;
    }
};

解法二:先找中点,翻转后半段再合并

class Solution {
public:
    void reorderList(ListNode* head){
        if(!head){return ;}
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* preNode = nullptr;
        ListNode* p = slow->next;
        slow->next = nullptr;
        while(p){
            ListNode* next = p->next;
            p->next = preNode;
            preNode = p;
            p = next;
        }
        ListNode* res = new ListNode(-1);
        while(preNode){
            res->next = head;
            head = head->next;
            res = res->next;
            res->next = preNode;
            preNode = preNode->next;
            res = res->next;
        }
        res->next = head;
        head = res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值