博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode学习笔记(143. 重排链表)
阅读量:4049 次
发布时间:2019-05-25

本文共 1967 字,大约阅读时间需要 6 分钟。

在这里插入图片描述

解法一:引入栈和队列的性质,缺点就是引入大量的额外空间;

/** * 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
q_data; stack
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; }};

转载地址:http://fvyci.baihongyu.com/

你可能感兴趣的文章
Jenkins + Docker + SpringCloud 微服务持续集成(一)
查看>>
Jenkins + Docker + SpringCloud 微服务持续集成 - 单机部署(二)
查看>>
Jenkins + Docker + SpringCloud 微服务持续集成 - 高可用集群部署(三)
查看>>
Golang struct 指针引用用法(声明入门篇)
查看>>
Linux 粘滞位 suid sgid
查看>>
C#控件集DotNetBar安装及破解
查看>>
Winform皮肤控件IrisSkin4.dll使用
查看>>
Winform多线程
查看>>
C# 托管与非托管
查看>>
Node.js中的事件驱动编程详解
查看>>
mongodb 命令
查看>>
MongoDB基本使用
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
nodejs Stream使用中的陷阱
查看>>
MongoDB 数据文件备份与恢复
查看>>
数据库索引介绍及使用
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>