题目:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
关键思路:
理解一下,一个链表要反转,首先要将全部节点遍历一遍,这种规范的情况下,最好就是实用while进行数据深层遍历。
1)顺序取链表所有节点,并将当前节点的next直接指向newHead(新构造的链表); 出于性能的考虑,不是重新构造所有节点,只是重塑节点间的指向。
2)这就有一个问题,当前节点p既需要向后重新赋值p.next,又需要重置next指向。怎么解决呢?加一个临时堆空间q,来临时放置当前节点。
解:
/**
* 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}
*/
function reverseList(head) {
const newHead = null;
const q = null;
while (head) {
q = head; // 当前节点
head = head.next; // 当前节点后移
q.next = newHead// 当前节点的next重新指向当前newHead
newHead = q // 更新newHead
}
return newHead;
}
———— 前端、Javascript实现、算法、刷题、leetcode