Reverse Linked List - LeetCode
주어진 단일 연결 리스트의 헤드가 주어졌을 때, 리스트를 역순으로 만들고 역순으로 된 리스트를 반환하세요.
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
풀이방법
prev 변수는 역순으로 연결된 노드들의 첫 노드를 가리키고, current 변수는 현재 노드를 가리킵니다.
반복문을 통해 현재 노드의 next를 역순으로 연결하고, prev를 현재 노드로 이동합니다.
마지막에 prev를 반환하여 역순으로 연결된 리스트를 얻습니다.
/**
* 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 beforeNode = null;
while(head != null){
ListNode nextNode = head.next;
head.next = beforeNode;
beforeNode = head;
head = nextNode;
}
return beforeNode;
}
}
2130. Maximum Twin Sum of a Linked List (0) | 2023.11.19 |
---|---|
328. Odd Even Linked List (0) | 2023.11.18 |
649. Dota2 Senate (0) | 2023.11.18 |
933. Number of Recent Calls (0) | 2023.11.17 |
735. Asteroid Collision (0) | 2023.11.16 |