-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
迭代
迭代方法需要设置当前节点的前一个节点 prev,当前节点 cur,以及每次改变指向前先缓存当前节点的下一个节点,方便后续节点移动。改变指向后,将缓存的下一个节点赋值给当前节点
var reverseList = function(head) {
let prev = null
let cur = head
while (cur !== null) {
let tempNext = cur.next
cur.next = prev
prev = cur
cur = tempNext
}
};递归
递归思想主要是先递归至链表末尾,反向一步步将指针指到上一个元素上。
var reverseList = function(head) {
if (head === null || head.next === null) return head
const p = reverseList(head.next)
head.next.next = head
head.next = null
return p
};Reactions are currently unavailable