当前位置:网站首页>[leetcode ladder] linked list · 021 merge two ordered linked lists
[leetcode ladder] linked list · 021 merge two ordered linked lists
2022-07-25 21:41:00 【kikokingzz】

Title Description :
Merge two ascending linked lists into a new Ascending Link list and return . The new linked list is made up of all the nodes of the given two linked lists .
Example 1:

Input :l1 = [1,2,4], l2 = [1,3,4]
Output :[1,1,2,3,4,4]Example 2:
Input :l1 = [], l2 = []
Output :[]Example 3:
Input :l1 = [], l2 = [0]
Output :[0]Topic link :
Their thinking :
Conventional method 1: Create a new linked list to receive
I think this method should be the most basic approach , Use four pointers to operate , Two pointers are used to traverse the original linked list , A pointer is used to identify the header of the new linked list , Another pointer is used to identify the end of the new linked list , Facilitate the tail insertion of new nodes .
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){ struct ListNode*n1=list1; //n1 Pointers are used to traverse list1 struct ListNode*n2=list2; //n2 Pointers are used to traverse list2 struct ListNode*newHead=NULL; struct ListNode*tail=NULL; while(n1&&n2) // When n1 or n2 There is one for NULL Jump out of the loop { if(n1->val<=n2->val) // When n1 The value of the node pointed to is less than or equal to n2 after { if(newHead==NULL) // When the new linked list is empty { newHead=n1; // take n1 As the head node of the new linked list tail=n1; n1=n1->next; } else // When the new linked list is not empty { tail->next=n1; // Connect the tail node of the new linked list to n1 tail=n1; n1=n1->next; } } else // When n1 The node value pointed to is greater than n2 when { if(newHead==NULL) // When the new linked list is empty { newHead=n2; // take n2 As the head node of the new linked list tail=n2; n2=n2->next; } else // When the new linked list is not empty { tail->next=n2; // Connect the tail node of the new linked list to n1 tail=n2; n2=n2->next; } } } if(newHead==NULL) // It shows that a linked list is empty at the beginning { if(n1==NULL) return n2; else if(n2==NULL) return n1; else if(n1==NULL&&n2==NULL) return NULL; } if(n1==NULL) tail->next=n2; if(n2==NULL) tail->next=n1; return newHead; }
To sum up : We found that this problem is slightly longer , It is because we need to discuss that the new chain header pointer may or may not be empty , For the problem that the head node of the new linked list may be empty , We must be here 【 Remove linked list elements 】 It has been introduced in this sentence , Using sentinel method can greatly simplify the above code .
Conventional method 2: Sentinel law
To simplify the above operation , In addition to establishing a sentry post , In fact, we only need to set two pointers ,n1 and n2 The pointer can use the original list1 and list2 To replace , Because of the result of this problem, we don't need to return to the original linked list , Just return a new merged linked list .
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){ struct ListNode* newHead=NULL,*tail=NULL; newHead=tail=(struct ListNode*)malloc(sizeof(struct ListNode));// At first tail and newHead Point to the same dynamic node space while(list1&&list2) // When list1 or list2 There is a null jump out of the loop { if(list1->val<=list2->val) { if(tail==NULL) // When the new linked list is empty { newHead->next=tail=list1; // take list1 The node pointed to is linked after the sentinel } else // When the new linked list is not empty { tail->next=list1; // take list1 The node pointed to is directly linked after the new linked list tail=list1; } list1=list1->next; //list1 Take a step back } else { if(tail==NULL) { newHead->next=tail=list2; } else { tail->next=list2; tail=list2; } list2=list2->next; } } if(list1==NULL) tail->next=list2; if(list2==NULL) tail->next=list1; struct ListNode* list=newHead->next; // Define a list The pointer points after the sentinel node free(newHead); //free Drop the sentinel node return list; }
To sum up : The cleverness of using sentinel method here is that it will tail and newHead All point to the same sentinel node space . For example, when there is a list It's empty time , Cannot enter at this time while loop , But you can enter with while The program that jumps out after the loop shares the same piece of code , Without classified discussion , This is because at first tail and newHead It points to the same sentinel node space , So for those programs that don't enter the loop , Their execution tail->next=list1, It's equivalent to executing newHead->next=list1. Eventually they and those enter while The procedure of the loop is the same , Finally, share one return newHead->next Statement can realize output operation .
边栏推荐
- [database] index
- Detailed explanation of several ideas for implementing timed tasks in PHP
- 【面试:并发篇25:多线程:volatile】可见性
- Research on the scheme of MySQL advanced (VIII) sorting problem
- mysql导入数据时已改成csv utf8文件且文件名为英文,为什么还是导入失败
- Record the transfer of domain names from Alibaba cloud service providers to Huawei cloud
- Interface testing tool restlet client
- Optimization analysis of storage structure and IO performance of openharmony littlefs file system
- 【leetcode天梯】链表 · 021 合并两个有序链表
- Interviewer of large factory: how to quickly query a table with tens of millions of data?
猜你喜欢

Detailed explanation of Ag search tool parameters

Zero basic learning canoe panel (17) -- panel CAPL function

Vivo official website app full model UI adaptation scheme

How to implement distributed locks with redis?

Pyg tutorial (8): calculate a more efficient sparse matrix form

919. 完全二叉树插入器 : 简单 BFS 运用题

如何用 Redis 实现分布式锁的?

Per capita Swiss number series, Swiss number 4 generation JS reverse analysis

Advanced technology management - how can the team be broken?

Babbitt | metauniverse daily must read: the popularity of virtual people has decreased, and some "debut is the peak", and the onlookers have dispersed
随机推荐
All non isomorphic subgraphs of a directed complete graph of order 3 (number of different hook graphs)
[interview: concurrent 25: multithreading: volatile] visibility
接口测试工具 restlet client
立创EDA——我为什么要学EDA
How will Web3 change the future of people?
零基础学习CANoe Panel(17)—— Panel CAPL Function
Stm3 (cubeide) lighting experiment
Naming rules for BSP of Quanzhi chip
ES6 -- Deconstruction assignment
Research: more than 70% of doctors are still prescribing unsafe antibiotic drugs
Airtest solves the problem that a password needs to be entered in the process of "automatic packaging" (the same applies to random bullet frame processing)
数据库sql语句练习题「建议收藏」
如何自动生成短链?如何在线批量生成带UTM参数的链接?
Creation and destruction of function stack frames
How to copy all files in one folder to another folder
How to automatically generate short chains? How to generate links with UTM parameters online in batches?
我也是醉了,Eureka 延迟注册还有这个坑!
函数栈帧的创建和销毁
Please give an example of how to optimize MySQL index (sqlserver index optimization)
全志芯片bsp命名规则
https://leetcode.cn/problems/merge-two-sorted-lists/

