Skip to content

Latest commit

 

History

History
41 lines (35 loc) · 722 Bytes

1.reverse-linked-list.md

File metadata and controls

41 lines (35 loc) · 722 Bytes

Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

JavaScript
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let newList = null;
    let cur = head;
    let tempNext = null;
    while(cur!==null){
        tempNext = cur.next;
        cur.next = newList;
        newList = cur;
        cur = tempNext;
    }
    return newList;
};