Problem:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
-Summary-
1. Keep track of current / prev (copy the original list in the curr and prev)
2. Update and move the head (original)
3. Return prev
-Other iterative solution-
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
node, prev = head, None
while node:
next, node.next = node.next, prev
prev, node = node, next
return prev
-Recursive solution-
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(node: ListNode, prev: ListNode = None) -> ListNode:
if not node:
return prev
next, node.next = node.next, prev
return reverse(next,node)
return reverse(head)
정답을 보니 recursive 하게 푸는 방법도 있었다.
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글
LeetCode. Palindrome Linked List [Linked List] (0) | 2020.06.04 |
---|---|
LeetCode. Merge Two Sorted Lists [Linked List] (0) | 2020.06.03 |
LeetCode. Remove Nth Node From End of List [Linked List] (0) | 2020.06.03 |
LeetCode. Delete Node in a Linked List [Linked List] (0) | 2020.06.03 |
LeetCode. Count and Say [String] (0) | 2020.06.03 |
댓글