https://leetcode.com/problems/reverse-linked-list/description/
Reverse Linked List - LeetCode
Can you solve this real interview question? 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] O
leetcode.com
문제 요약 : 연결 리스트 뒤집기
풀이 로직은 다음과 같다.
- 연결 리스트를 돌면서 result 변수에 거꾸로 담아가기
# 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]:
result = None
cur = head
while cur:
temp = result
result = ListNode(cur.val)
result.next = temp
cur = cur.next
return result
- 시간복잡도 : O(n)
- 개선할 점 : 임시 변수 temp를 쓰지 않고, 바로 swap 하면 더 깔끔하겠다
'알고리즘' 카테고리의 다른 글
[프로그래머스] 올바른 괄호 (0) | 2023.04.23 |
---|---|
[leetcode/python] 21번 Merge Two Sorted Lists (0) | 2023.04.13 |
[leetcode/python] 234번 Palindrome Linked List (0) | 2023.04.13 |
[leetcode/python] 561번 Array Partition (0) | 2023.04.13 |
[leetcode/python] 42번 Trapping Rain Water (0) | 2023.04.13 |