-
[알고리즘] #Remove Nth Node From End of List■ Algorithm 2022. 8. 5. 18:23
문제 출처: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Remove Nth Node From End of List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 해석
연결 리스트의 head가 주어졌을 때, 끝에서 n번째 노드를 지운 head를 리턴하라.
풀이
1) 우선 전체 node의 갯수를 알기 위해 노드 전체를 순회하면서 전체 노드의 갯수를 count에 저장한다.
2) 지우려는 노드 앞에 몇 개의 노드가 있는지 count 값을 count-n 으로 바꿔준다.
2-1) Testcase에 있는 [1], 1 이런 케이스를 걸러내기 위해 2)에서 계산한 count값이 0 이하이면 head의 next 노드를 리턴한다.
3) currentNode 변수에 head 값을 넣어주고, 지우려는 노드 바로 앞 노드까지 오도록 while문을 이용해 구현한다.
4) currentNode의 next 노드 값을 unwantedNode에 저장한 뒤, currentNode의 next 노드에 unwantedNode의 next 노드가 오도록 구현한다.
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val === undefined ? 0 : val) * this.next = (next === undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} n * @return {ListNode} */ var removeNthFromEnd = function(head, n) { let node = head.next, count=1, run=0; while(node !== null){ count++; node = node.next; } count = count - n; if(count<=0){ return head.next; } let currentNode = head; while(run !== count-1){ currentNode = currentNode.next; run++; } let unwantedNode = currentNode.next; currentNode.next = unwantedNode.next; return head; };
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Palindrome Number (0) 2022.10.12 [알고리즘] #Longest Substring Without Repeating Characters (0) 2022.08.06 [알고리즘] #Middle of the Linked List (0) 2022.08.05 [알고리즘] #Reverse Words in a String III (0) 2022.08.05 [알고리즘] #Reverse String (0) 2022.08.05