# #Review old knowledge, move brick for a long time to a simple algorithm to change brain hee hee ~
Leecode link :leetcode-cn.com/problems/re…
Their thinking
We can first consider the inversion of two linked lists: we can simply point next of n+1 to n
‘Enter:… -> n -> n+1 ->…
Output:… n+1 -> n ->… `
To reverse multiple nodes, double pointer traverses the linked list. Repeat the above operation
The problem solving steps
1. Double-pointer traverses the linked list backwards and forwards. 2
code
First complete the traversal:
var reverseList = function(head){
let p1 = head
let p2 = null
while(p1){
p2 = p1
p1 = p1.next
}
}
Copy the code
Step 2: Point P1 back to P2
var reverseList = function(head){
let p1 = head
let p2 = null
while(p1){
const tmp = p1.next
p1.next = p2 // next points to p2, so p1 cannot be traversed further, so a temporary variable is needed to save p1's value
p2 = p1
p1 = tmp
}
return p2 // Finally return the reversed list
}
Copy the code
Time complexity and space complexity
Time complexity: O(n) Space complexity: O(1)