File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : post
3
+ title : (Leetcode) 19 - Remove Nth Node From End of List
4
+ categories : [스터디-알고리즘]
5
+ tags :
6
+ [
7
+ 자바,
8
+ java,
9
+ 리트코드,
10
+ Leetcode,
11
+ 알고리즘,
12
+ algorithm,
13
+ linked list,
14
+ index,
15
+ node,
16
+ ]
17
+ date : 2024-06-10 01:00:00 +0900
18
+ toc : true
19
+ ---
20
+
21
+ 기회가 되어 [ 달레님의 스터디] ( https://github.com/DaleStudy/leetcode-study ) 에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
22
+
23
+ [ https://neetcode.io/practice ] ( https://neetcode.io/practice )
24
+
25
+ ---
26
+
27
+ [ https://leetcode.com/problems/remove-nth-node-from-end-of-list/ ] ( https://leetcode.com/problems/remove-nth-node-from-end-of-list/ )
28
+
29
+ ## 내가 작성한 풀이
30
+
31
+ 처음에는 linked list 의 길이를 재고, 어떤 node를 삭제해야하는지 확인하여 삭제하도록 하였다.
32
+
33
+ ``` java
34
+ class Solution {
35
+ public ListNode removeNthFromEnd (ListNode head , int n ) {
36
+ ListNode current = head;
37
+ int length = 0 ;
38
+ while (current != null ) {
39
+ length++ ;
40
+ current = current. next;
41
+ }
42
+
43
+ if (length == 1 ) {
44
+ return null ;
45
+ }
46
+
47
+ if (length == n) {
48
+ return head. next;
49
+ }
50
+
51
+ int removeIndex = length - n;
52
+ int pointer = 0 ;
53
+ current = head;
54
+ while (pointer < removeIndex - 1 ) {
55
+ current = current. next;
56
+ pointer++ ;
57
+ }
58
+ current. next = current. next. next;
59
+ return head;
60
+ }
61
+ }
62
+ ```
63
+
64
+ ### TC, SC
65
+
66
+ 시간 복잡도는 O(n)이고, 공간 복잡도는 O(1)이다.
You can’t perform that action at this time.
0 commit comments