MakerHyeon

[LeetCode] 206. Reverse Linked List 본문

Algorithm/LeetCode

[LeetCode] 206. Reverse Linked List

유쾌한고등어 2023. 1. 10. 18:07

https://leetcode.com/problems/reverse-linked-list/

 

Reverse Linked List - LeetCode

Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list.   Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: [https://asset

leetcode.com

미쳤다.재귀를 이문제를 통해 처음으로 완전히 이해했다!!!재귀가 이런거였군...!!!

개초보인 나에게는 이순간이 너무 감동적이다...

 

먼저, 이문제는 Two Pointer를 사용하는방법과 재귀를 사용하여 푸는 방법 두가지가 존재한다.

Two Pinter는 간단하다.

1.처음 prev는 none,curr은 현재노드를가리킨다. (prev->cur)

2. curr이 있다면 prev<-cur 로순서를 바꾸고, prev와 cur을 한칸씩이동.


이제 재귀를 살펴보도록 하자.

재귀에서 가장 중요한것은,문제를 제일작은 단위로 쪼개서 하나씩 경우를 넓혀가는것이다.

아래 그림처럼 먼저 노드가한개일때,두개일때를 고려해본다.

우선 제일먼저 설정해야할 base조건은 curr=null이면 return prev.이다.

그럼 반복되는 것이 보인다. curr!=null이면 한칸씩옮긴후 동일한과정을 반복한다...!

그럼 이부분에 재귀를 걸면된다.

 

 

 

 


SOLUTION CODE

1. Two Pointers

# PYTHON Code

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev,curr = None,head

        while curr:
            nxt=curr.next
            curr.next = prev
            prev=curr
            curr = nxt

        return prev

 

# C++ Code

/**
 * 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* cur = head;
        ListNode* pre = NULL;
        while (cur) {
            ListNode* nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
};

 

2. Recursion

# PYTHON Code

class Solution:
    def reverseList(self, node, prev=None) -> Optional[ListNode]:
        if curr=None:
            return prev
        else:
            next = curr.next
            curr.next=prev
            return self.reverseList(next,prev=curr) # 한칸씩옮겨주기,그리고같은과정반복

 

# C++ Code

/**
 * 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) {}
 * };
 */

ListNode* recursion_func(ListNode* cur,ListNode* prev){
    if(cur == NULL){
        return prev;
    }
    ListNode* next = cur->next; // cur->next임시저장
    cur->next=prev; // prev<-curr
    ListNode* head = recursion_func(next,cur); // 한칸씩 옮겨 같은과정반복(head==prev)
    return head;

}

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        return recursion_func(head,NULL);
    }
};

 

 

 

'Algorithm > LeetCode' 카테고리의 다른 글

[LeetCode] 238. Product of Array Except Self  (0) 2023.01.19
[LeetCode] 21. Merge Two Sorted Lists  (0) 2023.01.19
[LeetCode] 20. Valid Parentheses  (0) 2023.01.06
[LeetCode] 155. Min Stack  (0) 2023.01.05
[LeetCode] 36. Valid Sudoku  (0) 2023.01.04
Comments