Nuggets team number online, help you Offer impromptu! Click on theCheck the details
1. Title Description
Reverse a single linked list. Example: input: 1 - > 2 - > 3 - > 4 - > 5 - > NULL output: 5 - > 4 - > 3 - > 1 - > 2 - > NULLCopy the code
Second, train of thought analysis
We can start by inverting two nodes in the linked list, such as:... n, n + 1, ... . n + 1, n, ... N.ext = n Reverses multiple nodes: Double Pointers traverse the list, repeating as if reversing two nodesCopy the code
Three, the solution code
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * * *@param {ListNode} head
* @return {ListNode}* /
var reverseList = function(head) {
let p1 = head;
let p2 = null;
while(p1) {
const temp = p1.next
p1.next = p2
p2 = p1
p1 = temp
}
return p2
};
Copy the code
Four,
- Reversing a linked list can be started by reversing two nodes and then iterating through the operation with a double pointer.
- Practice every day and keep learning