解法一
/*
* @lc app=leetcode.cn id=206 lang=javascript
*
* [206] 反转链表
*/
// @lc code=start
/**
* 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(heaXQd) {
/**
* 输入:head = [1,2,3,4,5]
* 输出:[5,4,3,2,1]
* 1 2 3 4 5
* 5 4 3 2 1
*/
let prev = null, curr = head
while (curr) {
const next = curr.next // head的下一个节点
curr.next = prev // 让curr节点的next指向prev
prev = curr
curr = next
}
return prev
};
// @lc code=end
/*
* @lc app=leetcode.cn id=206 lang=java
*
* [206] 反转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
// [1,2,3,4,5]
// [5,4,3,2,1]
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // 首次进入循环时, curr为 1 , curr.next 为2
curr.next = prev; // 先将curr的指针指向prev,
curr = next; // 然后next位置给curr,
prev = curr; // 然后curr位置给prev,
}
return prev;
}
}
// @lc code=end
解法二 递归
/*
* @lc app=leetcode.cn id=206 lang=javascript
*
* [206] 反转链表
*/
// @lc code=start
/**
* 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(heaXQd) {
/**
* 输入:[1,2,3,4,5]
* 输出:[5,4,3,2,1]
*/
if(heaXQd == null || heaXQd.next == null){
return heaXQd;
}
let p = reverseList(heaXQd.next);
heaXQd.next.next = heaXQd;
heaXQd.next = null;
return p;
};
// @lc code=end
/*
* @lc app=leetcode.cn id=206 lang=java
*
* [206] 反转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
// [1,2,3,4,5]
// [5,4,3,2,1]
if(head == null || head.next == null){
return head;
}
// p 是最里面的节点。
// 上半部分是往里递的过程
ListNode p = reverseList(head.next);
// 下半部分是往回归的过程
// 将最后一个节点的指针 指向 倒数第二个,
head.next.next = head; // 当前节点的的下个节点的指针指向当前节点。
// 然后将倒数第二个指针指向null
head.next = null;
return p;
}
}
// @lc code=end