LeetCode/Linked List
[Easy] 206. Reverse Linked List
Developer07
2022. 8. 28. 01:14
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;
}
}