19. Remove Nth Node From End of List

JJ·2021년 1월 20일
0

Algorithms

목록 보기
72/114
/**
 * 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) {
        int num = 0;
        ListNode dummy = new ListNode(0);
        dummy.next = head; 
        ListNode cur = dummy;
        while (cur.next != null) {
            cur = cur.next;
            num++;
        }
        
        if (num < 2) {
            return null; 
        }
        
        ListNode cur2 = dummy;
        for (int i = 0; i < num - n; i++) {
            cur2 = cur2.next;
        }
        
        cur2.next = cur2.next.next; 
        
        return dummy.next; 
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
Memory Usage: 36.7 MB, less than 95.29% of Java online submissions for Remove Nth Node From End of List.

One pass로는 모르겠고 two pass로 일단 풀어봤읍니다..

/**
 * 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) {
        int num = 1;
        ListNode cur = head;
        ListNode cur2 = head;
        
        while (cur.next != null) {
            num++;
            cur = cur.next;
            
            if (num > n + 1) {
                cur2 = cur2.next;
            }
        }
        
        if (num == n) {
            return head.next;
        } else {
            cur2.next = cur2.next.next;
            return head; 
        }
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
Memory Usage: 36.9 MB, less than 64.03% of Java online submissions for Remove Nth Node From End of List.

생각 좀 해보다가 누가 파이선으로 one pass를 생각해놨길래 java로 써봤읍니다..

사람들 머리 잘 굴리네요 ㅎㅎ

0개의 댓글