1. 첫 번째 코드
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int cnt = 1;
ListNode* from = new ListNode();
from->next = head;
ListNode remove = *head;
while (remove.next) {
remove = *remove.next;
cnt++;
}
remove = *from;
for (int i = 0; i < cnt - n - 1; i++) {
remove = *remove.next;
}
ListNode* tmp = remove.next;
if (tmp->next and n != cnt) tmp->next = tmp->next->next;
else head = head->next;
return head;
}
};
|
cs |
2.
2. 완성한 코드
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* p = head, *q = head; for (int i = 0; i < n; i++) p = p->next; if (!p) return head->next; while (p->next) { p = p->next; q = q->next; } q->next = q->next->next; return head; } }; | cs |
'Leetcode' 카테고리의 다른 글
LeetCode 1114. Print in Order [C++/ promise] (0) | 2022.06.03 |
---|---|
Merge Two Sorted Lists / leetcode / c++ (0) | 2022.06.01 |
leetcode Reverse Integer (0) | 2022.05.29 |
Add Two Numbers leetcode 2 (0) | 2022.05.29 |
[MySQL] 176. Second Highest Salary[LeetCode Medium] - 1 (0) | 2022.05.25 |