Leetcode 206번 문제는 주어진 연결 리스트를 반대로 뒤집는 문제이다. 연결 리스트의 reference to the head가 주어진다.
#풀이
# Iteratively (반복) 풀이
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while(head != null){
ListNode nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
}
# recursively (재귀적) 풀이
class Solution {
public ListNode reverseList(ListNode head) {
// base case
if(head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
'LeetCode > Linked List' 카테고리의 다른 글
[Easy] 21. Merge Two Sorted Lists (0) | 2022.11.15 |
---|---|
[Medium] 142. Linked List Cycle II (0) | 2022.09.02 |
[Easy] 141. Linked List Cycle (0) | 2022.08.29 |
[Medium] 2. Add Two Numbers (0) | 2022.08.25 |
[Easy] 234. Palindrome Linked List (0) | 2022.08.24 |