알고리즘/알고리즘 공부(JAVA)

Remove Nth Node From End of List(JAVA)

소소한필통 2025. 4. 6. 23:28

URL : https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/

 

 

 

문제풀이

- 단방향 linked-list와 n이 주어지며, 뒤에서 n번째 값을 제거한 linked-list를 반환해라!

- null값을 받을것도 고려해야함 -> 리스트가 하나밖에없는 값을 대비하기 위해서 dummy데이터를 젤 앞에 넣음

- 그러고 더미데이터 다음을 주어진 linked-list와 연결

- first, last두개를 지정하기 last는 n만큼 먼저 간 포인터이고, first는 last가 끝에 도착했을 때 n만큼앞에 있는 포인터임. 이 두가지의 조합으로 뒤에서 n만큼 앞에있는 요소를 파악이 가능함.

- 해당 지점을 찾앗을때 해당 포인터를 없애고 다음포인터로 연결하기

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode first = dummy;
            ListNode last = dummy;
            for (int i=0; i < n; i++){
                last = last.next;
            }
            while (last.next != null){
                last = last.next;
                first = first.next;
            }
            
            first.next = first.next.next;
            
            return dummy.next;
        }
    }

'알고리즘 > 알고리즘 공부(JAVA)' 카테고리의 다른 글

Delete Node in a Linked List  (0) 2025.04.06
LeetCode(Single Number)  (0) 2025.03.15
LeetCode(Contains Duplicate)  (0) 2025.03.09
Leetcode(Rotate Array)  (0) 2025.03.08
backjoon_1546_평균 Using(Java)  (0) 2022.08.31