反转链表
给你单链表的头节点
head,请你反转链表,并返回反转后的链表。
示例1:
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
示例2:
输入: head = []
输出: []
数据结构
class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
}
思路:
此题目比较简单,如题描述,只需要将当前节点的指针指向前一个节点即可,其中需要中转保存下一个节点防止更换指针后丢失原本的next,开始时注意判空。
代码
function reverseList(head: ListNode | null): ListNode | null {
if(!head) return null;
let pre = null,cur = head;
while(cur){
const next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
};