Reverse Linked List - LeetCode
Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: [https://asset
leetcode.com
# 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]:
previous = None
while head != None:
temp = head
head = head.next
temp.next = previous
previous = temp
return previous
자료구조 Linked List를 사용
'알고리즘 > Leetcode' 카테고리의 다른 글
| [leetcode/python3] 876. Middle of the Linked List (0) | 2023.02.10 |
|---|---|
| [leetcode/python3] 21. Merge Two Sorted Lists (0) | 2023.02.08 |
| [leetcode/python3] 392. Is Subsequence (1) | 2023.01.25 |
| [leetcode/python3] 205. Isomorphic Strings (0) | 2023.01.25 |
| [leetcode/python3] 724. Find Pivot Index (0) | 2023.01.22 |