본문 바로가기
Web development/Algorithm

[LeetCode] Reverse Linked List (javascript)

by 자몬다 2021. 2. 26.

연결리스트 뒤집기.

 

좋은 풀이는 아니라고 생각하지만..

배열로 변환한 후 새로운 리스트를 만드는 방식으로 품.

/**
 * 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) {
    if(head==null) return head;

    let items = [];
    let curr = head;
    while(curr){
        items.push(curr.val);
        curr = curr.next;
    }
    
    let newList = new ListNode(items[items.length-1]);
    for(let i = items.length-2; i>-1; i--){
        newList.add(newList, items[i])
    }
    
    return newList
};

ListNode.prototype.add = (node, val) => {
    var curr;
    if(node.val === undefined){
        node.val = val;
    } else {
        curr = node;
        while(curr.next){
            curr = curr.next
        }
        curr.next = new ListNode(val);
    }
}

 

leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/

댓글