코딩테스트
10월 25일 - Reverse Linked List swift
알롱도담쓰
2023. 10. 25. 19:44
문제 설명
제한 조건
https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com
내 답안
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
if head == nil { return head }
var prev: ListNode? = nil
var head = head
var next: ListNode?
while head != nil {
next = head?.next
head?.next = prev
prev = head
head = next
}
return prev
}
}
접근 방법
포인터를 과거 노드 / 현재 노드 / 다음 노드 이렇게 3개를 만든다
현재 노드는 계속 다음으로 진행하고 (링크드리스트를 따라 -> 방향으로 계속 진행)
현재 노드를 중심으로 다음 노드 값, 과거노드 값을 설정해준다
다른 풀이