HZFE / algorithms-solving

1 stars 0 forks source link

2022-08-03 #5

Open github-actions[bot] opened 2 years ago

github-actions[bot] commented 2 years ago

206. Reverse Linked List

gongpeione commented 2 years ago

206 Reverse Linked List

/*
 * @lc app=leetcode id=206 lang=typescript
 *
 * [206] Reverse Linked List
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * 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)
 *     }
 * }
 */

function reverseList(head: ListNode | null): ListNode | null {
    let headPointer = head;
    let prev = null;

    while(headPointer) {
        // store the next node
        const next = headPointer.next;
        // point the next node of current head node to prev node
        headPointer.next = prev;
        // current head node become the prev node
        prev = headPointer;
        // next node become the head node
        headPointer = next;
    }

    return prev;
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms