当前位置:网站首页>Leetcode algorithm 147. insert and sort the linked list
Leetcode algorithm 147. insert and sort the linked list
2022-07-26 01:51:00 【Alex_ 12 hours a day 6 days a week】
Topic link :147. Insert and sort the linked list
Ideas
Algorithm : Insertion sort
data structure : Linked list
Ideas : Define a lastSorted The pointer points to the last ordered node , Let me define one more cur The pointer points to the node currently being judged , If the value of the last ordered node is less than the value of the node currently being judged , that lastSorted Pointers and cur Move the pointer back , Otherwise, it means that the current node needs to be inserted forward , So let's define a pre Node refers to the head node , If pre The next node value of is greater than cur Node value , Then we should put cur Insert into pre Just behind the node .
Code
C++
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == nullptr) {
return head;
}
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *lastSorted = head, *cur = head->next;
while (cur != nullptr) {
if (lastSorted->val <= cur->val) {
lastSorted = lastSorted->next;
} else {
ListNode *pre = dummyHead;
while (pre->next->val <= cur->val) {
pre = pre->next;
}
lastSorted->next = cur->next;
cur->next = pre->next;
pre->next = cur;
}
cur = lastSorted->next;
}
return dummyHead->next;
}
};
边栏推荐
猜你喜欢

Implementation of recommendation system collaborative filtering in spark

CPU的三种模式

Network layer 2 and layer 3 forwarding

Prime Ring Problem

IDEA如何快速删除最近打开的项目

推荐⼀款超好⽤的UI⾃动化⼯具: UiAutomator2!

pdf. JS introduction

Recommend a super good UI automation tool: uiautomator2!

网络之IP地址

SVN version control branch and merge function use
随机推荐
在Anaconda 中安装和使用R
学习笔记:原码, 反码, 补码
MPLS知识点
重发布基础与配置
C language enumeration types and unions
Proto conversion dart | project uses protobuf | fluent uses grpc
Worthington核酸酶、微球菌相关研究及测定方案
“蔚来杯“2022牛客暑期多校训练营2 个人题解集合
zeromq浅析
Niuke - bm39 serialized binary tree [hard]
How idea can quickly delete recently opened projects
G. Count the trains (thought set + two points)
Spark-SQL中根据年月日显示周几用date_format(date,‘u‘)
Protect syslog servers and devices
BGP知识点总结
软件加群验证
SVN版本控制分支、合并功能使用
Worthington产气荚膜梭菌神经氨酸酶的特征及测定
E. OpenStreetMap (2D monotone queue)
NFT market also began to diversify