当前位置:网站首页>[JS] - [linked list - application] - learning notes
[JS] - [linked list - application] - learning notes
2022-06-24 23:17:00 【Interesting learning】
【js】-【 Linked list - application 】- Learning notes
Statement : This note is based on the Nuggets brochure , If you want to learn more details , Please move https://juejin.cn/book/6844733800300150797
1 The combination of linked lists
describe :
Merge two ordered lists into a new ordered list and return . The new linked list is composed of all nodes of a given two linked lists
Input :
1->2->4,
1->3->4
Output :
1->1->2->3->4->4
Ideas :
The red arrow in the figure below indicates the process and direction of needle threading
- Create a new header node , Create a pointer
cur, As a needle- String the smaller node , The pointer moves forward , At present cur The pointer also moves forward
- Finally, handle the unfinished linked list , Spell last
const mergeTwoLists = function(l1, l2) {
#1 Define header node , Make sure the linked list can be accessed
let head = new ListNode()
// cur This is our one “ The needle ”
let cur = head
// “ The needle ” Start in l1 and l2 Shuttling between
while(l1 && l2) {
# 2.1 If l1 The node value of is small , String up first l1 The node of ,l1 Walk forward
if(l1.val<=l2.val) {
cur.next = l1
l1 = l1.next
} else {
#2.2 If l2 More hours , String up l2 node ,l2 Step forward
cur.next = l2
l2 = l2.next
}
#3 “ The needle ” After concatenating a node , Will also take a step forward
cur = cur.next
}
#4 Deal with the unequal length of the linked list
cur.next = l1!==null?l1:l2
// Return to the starting node
return head.next
};
2 Deletion of linked list nodes
1. Delete all duplicate elements
describe :
Given a sorted linked list , Delete all duplicate elements , So that each element only appears once .
Input :
1->1->2
Output :1->2
Input :
1->1->2->3->3
Output :1->2->3
const deleteDuplicates = function(head) {
#1 Set up cur The pointer , The initial position is the first node of the linked list
let cur = head;
#2 Traversing the linked list
while(cur != null && cur.next != null) {
if(cur.val === cur.next.val) {
# 2.1 If the value of the current node is equal to that of the following node ( repeat ), Delete the next node ( duplicate removal )
cur.next = cur.next.next;
} else {
# 2.2 If not repeated , Continue traversing
cur = cur.next;
}
}
return head;
};
2 Delete all nodes with duplicate numbers
describe :
Given a sorted linked list , Delete all nodes with duplicate numbers , Keep only the original list No recurring numbers
Input :
1->2->3->3->4->4->5
Output :1->2->5
Input :
1->1->1->2->3
Output :2->3
Ideas :
The first node of the linked list , Because there is no precursor node , We have no way to deal with it . Then we can use adummyNodes to solve this problem .
1 Definitiondummynode , Point to the head node ,curfromdummyTraverse
2. Meet the same , Record val Value , Start loop traversal , Delete the same . If not, skip
3 returndummy.next, That is, the starting node of the linked list
const deleteDuplicates = function(head) {
#1 In extreme cases :0 Or 1 Nodes , Will not repeat , Go straight back to
if(!head || !head.next) {
return head
}
#2 dummy On stage ,dummy Always point to the head node
let dummy = new ListNode()
dummy.next = head
#3 cur from dummy To traverse the
let cur = dummy
// When cur When there are at least two nodes behind
while(cur.next && cur.next.next) {
// Yes cur The latter two nodes are compared
if(cur.next.val === cur.next.next.val) {
// If the value is repeated , Then write down this value
let val = cur.next.val
// Repeatedly check whether the following elements repeat the value multiple times
while(cur.next && cur.next.val===val) {
// If you have any , Delete
cur.next = cur.next.next
}
} else {
// If not repeated , Normal traversal
cur = cur.next
}
}
// Return the starting node of the linked list
return dummy.next;
};
dummynode , Template code
const dummy = new ListNode()
// there head Is the original first node of the linked list
dummy.next = head
3 Delete the last of the linked list N Nodes ( Speed pointer )
describe :
Given a linked list , Delete the last of the linked list n Nodes , And return the head node of the list .
Given a linked list :
1->2->3->4->5, andn = 2.
When the penultimate node is deleted , Linked list becomes1->2->3->5.
Ideas :
- Definition dummy The node is the precursor of the head node , Both the speed and the speed of the pointer dummy Start
- Let's go first n Step ,
- The fast and slow pointers start to move synchronously ,
- Delete the successor of slow pointer , Countdown n Nodes
- return dummy.next, Head node
const removeNthFromEnd = function(head, n) {
#1 initialization dummy node , Point to the head node
const dummy = new ListNode()
dummy.next = head
#2 Initialize speed pointer , All pointing dummy
let fast = dummy
let slow = dummy
#3 Hurry up and walk slowly n Step
while(n!==0){
fast = fast.next
n--
}
#4 Go with the hands
while(fast.next){
fast = fast.next
slow = slow.next
}
#5 The slow pointer deletes its own successor node
slow.next = slow.next.next
// Return to header node
return dummy.next
};
4.0 Reverse of linked list ( Multi pointer )
describe :
Define a function , Enter the head node of a linked list , Invert the linked list and output the head node of the inverted linked list
Input :
1->2->3->4->5->NULL
Output :5->4->3->2->1->NULL
Ideas :
- Precursor node
pre, The current nodecur, Successor nodenextnextPoint topre, thenpreandcurContinue to move back- Finally back to
pre, Is the head node of the new linked list
const reverseList = function(head) {
#1 The initialization precursor node is null
let pre = null;
#2 Initialize the target node as the header node
let cur = head;
#3 As long as the target node is not null, Traversal must continue
while (cur !== null) {
// Make a note of next node
let next = cur.next;
// Reverse pointer
cur.next = pre;
// pre Take a step forward
pre = cur;
// cur Take a step forward
cur = next;
}
// After the reversal ,pre It will become the head node of the new linked list
return pre
};
4.1 Locally invert a linked list
describe :
Reverse from position m To n The linked list of . Please use a scan to complete the inversion .
Input :
1->2->3->4->5->NULL, m = 2, n = 4
Output :1->4->3->2->5->NULL
Ideas
- First define
dummy, findmThe precursor of , And save itlefthead- from
mAspre,cur Point topre.nextStart flipping- hold
leftHeadPoint topre,startPoint tocur
// The input parameter is the header node 、m、n
const reverseBetween = function(head, m, n) {
// Definition pre、cur, use leftHead To undertake the precursor node of the whole section
let pre,cur,leftHead
#1 dummy node
const dummy = new ListNode()
dummy.next = head
#2.0 p It's a cursor , Used to traverse the , At first it pointed to dummy, Go straight ahead m-1 Step , Go to the precursor node of the whole section
let p = dummy
for(let i=0;i<m-1;i++){
p = p.next
}
#2.1 Cache this precursor node to leftHead in
leftHead = p
let start = leftHead.next // start Is the first node of the inversion interval
pre = start// pre Point to start
cur = pre.next // cur Point to start Next node of
#3 Start repeating the reverse action
for(let i=m;i<n;i++){
let next = cur.next// Make a note of next node
cur.next = pre // Reverse pointer
pre = cur// pre Take a step forward
cur = next // cur Take a step forward
}
#4 leftHead The subsequent node of is now the first node of the inverted interval
leftHead.next = pre
start.next=cur // The last node after reversing the interval next Point to cur
return dummy.next // dummy.next Always point to the chain header node
};
5 Judge whether the linked list is looped
- Change the node ,
flag
const detectCycle = function(head) {
while(head){
if(head.flag){
return head;
}else{
head.flag = true;
head = head.next;
}
}
return null;
};
2. It can be used map simulation ( I like , Keep in mind )
const detectCycle = function(head) {
const visited = new Map();
while(head){
if(visited.has(head)){
return head;
}else{
visited.set(head)
head = head.next;
}
}
return null;
};
- Speed pointer
Let's go two steps , Slow pointer one step
If they are equal, there is a ring
const detectCycle = function(head) {
if(!head) return null;
let slow=head,fast=head;
#1 Go ahead before the end of the pointer
while (fast !== null) {
#2 Slow pointer one step , Let's go two steps
slow = slow.next;
if (fast.next !== null) {
fast = fast.next.next;
} else {
return null;
}
#3 If the fast and slow hands meet
if (fast === slow) {
let ptr = head;
while (ptr !== slow) {
ptr = ptr.next;
slow = slow.next;
}
return ptr;
}
}
return null;
};
Let's use an extra pointer
ptr.
start , It points to the head of the linked list
; And then , It andslowMove back one position at a time . Final , They will meet at the entry point .
边栏推荐
- Laravel user authorization
- Concurrent shared model management
- QT to place the form in the lower right corner of the desktop
- Écoutez le fichier markdown et mettez à jour Hot next. Page JS
- Daily practice (22): maximum sum of continuous subarrays
- golang convert map to json string
- Uip1.0 active sending problem understanding
- Sword finger offer 13 Range of motion of robot
- What kind of processor architecture is ARM architecture?
- Getting started with the go Cobra command line tool
猜你喜欢

Tech talk activity review kubernetes skills of cloud native Devops

【nvm】

Simulated 100 questions and online simulated examination of high voltage electrician examination in 2022

laravel 宝塔安全配置

2022 simulated 100 questions and simulated examination of high-altitude installation, maintenance and demolition

Blogs personal blog project details (servlet implementation)

【js】-【数组应用】-学习笔记

Theoretical analysis of countermeasure training: adaptive step size fast countermeasure training
![[JS] - [array, Stack, queue, Link List basis] - Notes](/img/c6/a1bd3b8ef6476d7d549abcb442949a.png)
[JS] - [array, Stack, queue, Link List basis] - Notes

Some updates about a hand slider (6-18, JS reverse)
随机推荐
Simulated 100 questions and online simulated examination of high voltage electrician examination in 2022
JD 618 conference tablet ranking list announced that the new dark horse brand staff will compete for the top three, learning from Huawei, the leader of domestic products
Do you need to improve your code reading ability? It's a trick
Financial management [4]
【js】-【栈、队-应用】-学习笔记
MySQL kills 10 people. How many questions can you hold on to?
Financial management [5]
01_SpingBoot 框架入门
07_ Springboot for restful style
Epics record reference 3 -- fields common to all records
Financial management [1]
jar中没有主清单属性
Listen to the markdown file and hot update next JS page
QT to place the form in the lower right corner of the desktop
Push markdown format information to the nailing robot
Case analysis: using "measurement" to improve enterprise R & D efficiency | ones talk
【js】-【数组应用】-学习笔记
案例解析:用「度量」提升企业研发效能|ONES Talk
websocket学习
A big factory interview must ask: how to solve the problem of TCP reliable transmission? 8 pictures for you to learn in detail




