# 🌈JSer LeetCode Trip: 206. Reverse Linked List

·  阅读 123

## 206. Reverse Linked List

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

## 实现

### 迭代

``````/**
* 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 prev = null
let curr = head
while(curr) {
// 变换之前先保存
const next = curr.next
curr.next = prev

prev = curr
curr = next
}
return prev
};

### 递归

``````/**
* 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) {

function reverse(prev, curr) {
if(!curr) return prev
const next = curr.next
curr.next = prev

// return reverse(prev = curr, curr = next)
return reverse(curr, next)
}
};