자료구조 알고리즘/코딩테스트
61. Rotate List
내공얌냠
2022. 6. 9. 11:03
https://leetcode.com/problems/rotate-list/
Rotate List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/**
* 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
반응형