Leetcode
Remove Nth Node From End of List, LeetCode, c++/cpp/c
치킨먹고싶어요
2022. 6. 1. 01:23
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 |