본문 바로가기

알고리즘/LeetCode

[JAVA] LeetCode 206 - Reverse Linked List

Reverse a singly linked list.

단일 연결 리스트를 뒤집어라.

 

 

풀이 방법

1. reverse된 결과를 리턴 할 ListNode 타입의 node를 선언한다.

2. 시작 노드부터 마지막 노드까지 각 노드가 순차적으로 head가 되어 반복문을 수행한다.

3. head 노드를 변경하기 전에 저장해 둔 temp 노드의 next값에 node를 할당한다.

4. 글로 백 번 적는 것보다, 한 번 그림으로 그리면서 로직을 따라가면 더 확실히 이해가 될 것이다!

 

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode node = null;
        while(head != null) {
            ListNode temp = head;
            head = head.next;
            temp.next = node;
            node = temp;
        }
        return node;
    }
}