LeetCode热题100-反转链表【JavaScript讲解】
题目:
解题思路:
反转链表就是将指向反转。
如上图示例一,我们需要循环,从1开始,1的节点指向null,2的节点指向1,直到head为null。
解题:
/**
* 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 pre = null;
let current = head;
while(current !== null){
let next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
};