Algorithm/PTUStudy

5주차. 연결 리스트(역순 연결 리스트)

지구우중 2023. 2. 6. 19:28

15. 역순 연결 리스트

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

📌문제
연결 리스트를 뒤집어라.



- 예제1
  📝입력

head = [1,2,3,4,5]



  💻출력

[5,4,3,2,1]



 - 예제2

  📝입력
 

head = [1,2]



  💻출력
 

[2,1]


    
📌풀이
0ms, 41.7mb

class Solution {
    public ListNode reverseList(ListNode head) {
       ListNode prev = null;

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

        return prev;
    }
}

- 팰린드롬 연결리스트에서 썼던 역순으로 뒤집어주는 알고리즘 그대로 사용했다.