Reverse Linked List

Yohan Kim·2021년 9월 22일
0

problem

주어진 링크드 리스트의 링크를 반대로 바꾸는 문제입니다.
https://leetcode.com/problems/reverse-linked-list/

solution

/**
 * 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) {}
 * };
 */
//problem no : 206
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return head;
        
        ListNode* prev = NULL;
        ListNode* next;
        
        while(head){
            next=head->next;
            head->next = prev;
            
            prev = head;
            head = next;
        }
        return prev;
    }
};

후기

처음에는 stack에 다 넣어놨다가 꺼내면서 바꿨는데,

모든 링크드 노드를 저장할 필요가 없었고,
노드를 타고 이동하면서 앞과 뒤만 바꾼다.

라는 것이 문제의 핵심이었던것같습니다.

profile
안녕하세요 반가워요!

0개의 댓글