“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”
Title 1
Delete duplicate element II from sorted linked list
There is a linked list in ascending order, and you are given the head node of the linked list. Please delete all the nodes in the linked list that have duplicate numbers, and only keep the original list that does not have duplicate numbers.
Returns a linked list of results, also in ascending order.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Example 2:
Input: head = [1,1,1,2,3]
Tip:
The number of nodes in the linked list is in the range [0, 300] -100 <= node. val <= 100 0 <= node. val <= 100\
Ask questions
- Delete nodes from linked lists?
Analysis of the
- define
pre
Pointer to a virtual head node, definedcur
Pointer tohead
node
- judge
cur
Whether the content of the node to which the pointer points is the same as the content of the node next to the current nodepre
with
Cur moves back at the same time.
- Judge again
cur
Whether the contents of the node to which the pointer points are the same as the contents of the node next to the current node, if socur
Move the hand back one bit
- Repeat execution when
cur
If the content of the node to which the pointer points is different from that of the node next to the current node, letpre
The node to which the pointer points pointscur
The next node to which the pointer points.
- At the same time mobile
pre
,cur
A pointer to thecur
Next node
-
Repeat until the next node of the node pointed to by cur is null.
-
Tidy it up
Code implementation
/** * @param {ListNode} head * @return {ListNode} */ var deleteDuplicates = function(head) { if (! head) return null let ret = new ListNode(-1,head) let pre = ret let cur = head while(cur && cur.next){ if(cur.next.val ! == cur.val){ cur = cur.next pre = pre.next }else{ while(cur && cur.next && cur.val === cur.next.val){ cur = cur.next } pre.next = cur.next cur = cur.next } } return ret.next };Copy the code
Topic 2
Print the linked list from end to end
Enter the head node of a linked list and return the value of each node from end to end (as an array).
Example 1:
Input: head = [1,3,2] output: [2,3,1]
Limitations:
The number of nodes in the list is in the range [0, 300] -100 <= node. val <= 100 item data ensures that the list is in ascending order
Analysis of the
- Walk through the list, pass
unshift
(Method adds the new item to the beginning of the array and returns the new length)
Code implementation
/** * @param {ListNode} head * @return {number[]} */ var reversePrint = function (head) { let arr = [] let temp = head while(temp ! == null) { arr.unshift(temp.val) node = temp.next } return arr }Copy the code