https://leetcode.com/problems/rotate-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* end = head;
ListNode* newTail = head;
ListNode* newHead;
int cnt = 1;
while(end->next) {
end = end->next;
cnt++;
}
k = k % cnt;
while(cnt - k - 1 != 0) {
newTail = newTail->next;
cnt--;
}
end->next = head;
newHead = newTail->next;
newTail->next = nullptr;
return newHead;
}
};
아래 것은 처음 것. test만 통과하고 wrong answer.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* end = head;
ListNode* tempNext = head;
ListNode* tempPrev = head;
int cnt = -1;
while(end->next) {
end = end->next;
cnt++;
}
while(cnt != 0) {
tempPrev = tempNext;
tempNext = tempPrev->next;
cnt--;
}
tempPrev->next = nullptr;
end->next = head;
head = tempNext;
return head;
}
};
728x90
반응형
'자료구조 알고리즘 > 코딩테스트' 카테고리의 다른 글
1571. Warehouse Manager (0) | 2022.06.18 |
---|---|
198. House Robber (0) | 2022.06.11 |
1741. Find Total Time Spent by Each Employee (0) | 2022.06.09 |
607. Sales Person (0) | 2022.06.03 |
197. Rising Temperature (0) | 2022.06.03 |