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: []
Constraints:
- The number of nodes in the list is the range [0, 5000].
- -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
# 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: Optional[ListNode]) -> Optional[ListNode]:
cprev=None
curr=head
while curr:
cnext=curr.next
curr.next=cprev
cprev=curr
curr=cnext
return cprev
'알고리즘 문제 > Leetcode' 카테고리의 다른 글
21. Merge Two Sorted Lists (0) | 2022.12.29 |
---|---|
917. Reverse Only Letters (0) | 2022.12.29 |
74. Search a 2D Matrix (0) | 2022.12.28 |
367. Valid Perfect Square (0) | 2022.12.28 |
441. Arranging Coins (0) | 2022.12.28 |