Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[친환경사과] Week 7 #923

Merged
merged 5 commits into from
Jan 25, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions reverse-linked-list/EcoFriendlyAppleSu.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package leetcode_study

/*
* Node를 역순으로 만드는 문제
* 추가 저장 공간을 사용해 노드를 채워 둔 뒤 역행하면서 포인터 값을 변경하는 방법으로 해결
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가적인 저장 공간을 사용하지 않고도 문제를 해결해보면 좋을 것 같아요

* 시간 복잡도: O(n)
* -> 새로운 공간에 값을 추가하는 반복문: O(n)
* -> 각 노드에 접근하여 포인터 값을 변경하는 반복문: O(n)
* 공간 복잡도: O(n)
* -> 주어진 노드를 저장할 수 있을만큼 저장 공간 필요: O(n)
* */
fun reverseList(head: ListNode?): ListNode? {
val stack = mutableListOf<ListNode>()
var currentNode = head
if (head == null) return null

while (currentNode != null) {
stack.add(currentNode)
currentNode = currentNode.next
}


for (i in stack.size - 1 downTo 1) {
stack[i].next = stack[i-1]
}
stack[0].next = null
return stack[stack.size -1]
}
Loading