I am participating in the creation activity of the Nuggets newcomer to start the road of writing together.

Algorithms and Data structures – reverse linked lists

LeetCode: address

Topic request

Given the head node of a single linked list, reverse the list and return the reversed list.

Case 1:

Enter: head = [1.2.3.4.5] output: [5.4.3.2.1]
Copy the code

Example 2:

Enter: head = [1.2] output: [2.1]
Copy the code

Example 3:

Input: head = [] Output: []

Train of thought

Breadth first search, depth first search and so on are fixed patterns (routines).

In the process of writing, try to separate to write, add notes, ideas will not be chaotic.

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) { if (head == null || Next == null) return head let resHead = null // Let todoHead = head Let TMP = todoHead todoHead = todohead. next // Connect the disconnected node to the flipped list tmp.next = resHead resHead = tmp } return resHead };Copy the code