728x90
반응형
https://leetcode.com/problems/reverse-linked-list/description/
문제
문제 분석
- 재귀를 이용해서, 또는 반복문을 이용해서 풀 수 있습니다.
풀이 1 (재귀)
/**
* 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* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
/**
* 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 {
private:
ListNode* reverse(ListNode* curr, ListNode* prev){
if(curr == nullptr){
return prev;
}
ListNode* next = curr->next;
curr->next = prev;
return reverse(next, curr);
}
public:
ListNode* reverseList(ListNode* head) {
return reverse(head, nullptr);
}
};
풀이2 (반복문)
/**
* 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* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
if(head == nullptr){
return curr;
}
while(curr){
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 24. Swap Nodes in Pairs (0) | 2024.08.17 |
---|---|
[LeetCode] C++ 2. Add Two Numbers (0) | 2024.08.17 |
[LeetCode] C++ 21. Merge Two Sorted Lists (0) | 2024.08.16 |
[LeetCode] C++ 234. Palindrome Linked List (0) | 2024.08.16 |
[LeetCode] C++ 121. Best Time to Buy and Sell Stock (0) | 2024.08.16 |