연결리스트 뒤집기.
좋은 풀이는 아니라고 생각하지만..
배열로 변환한 후 새로운 리스트를 만드는 방식으로 품.
/**
* 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/
'Web development > Algorithm' 카테고리의 다른 글
[LeetCode] Palindrome Linked List (javascript) (0) | 2021.02.26 |
---|---|
[LeetCode] Merge Two Sorted Lists (javascript) (0) | 2021.02.26 |
[LeetCode] Remove Nth Node from End of List (javascript) (0) | 2021.02.26 |
[LeetCode] Delete Node in a Linked List (javascript) (0) | 2021.02.26 |
[LeetCode] Longest Common Prefix (javascript) (0) | 2021.02.26 |
댓글