[LeetCode] Reverse Linked List

아르당·2025년 10월 21일

LeetCode

목록 보기
50/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

단일 연결 리스트인 head가 주어졌을 때, 리스트를 반전하고 반전된 리스트를 반환해라.

Example

#1

Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]

#2

Input: head = [1, 2]
Output: [2, 1]

#3
Input: head = []
Output: []

Constraints

  • 리스트에 노드의 숫자는 0에서 5000 범위에 있다.
  • -5000 <= Node.val <= 5000

Solved

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode node = null;

        while(head != null){
            ListNode next = head.next;
            head.next = node;
            node = head;
            head = next;
        }

        return node;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글