Skip to content

Commit 64397e6

Browse files
committed
Add reverse-linked-list sol
1 parent 6f3f826 commit 64397e6

File tree

1 file changed

+73
-3
lines changed

1 file changed

+73
-3
lines changed

reverse-linked-list/shinsj4653.py

Lines changed: 73 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,85 @@
11
"""
22
[문제풀이]
33
# Inputs
4-
4+
- head of singly linked list
55
# Outputs
6-
6+
- return the reversed list
77
# Constraints
8-
8+
- The number of nodes in the list is the range [0, 5000].
9+
- 5000 <= Node.val <= 5000
910
# Ideas
11+
1. 스택 활용?
12+
첫 head의 노드부터 스택에 넣기
13+
맨 끝 도달하면
14+
스택 pop 하면서 새 리스트 만들기??
15+
16+
마지막 요소를 인식 못하나?
1017
1118
[회고]
1219
1320
"""
21+
# 첫 제출
22+
23+
# Definition for singly-linked list.
24+
# class ListNode:
25+
# def __init__(self, val=0, next=None):
26+
# self.val = val
27+
# self.next = next
28+
class Solution:
29+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
30+
31+
ret = ListNode()
32+
ret_head = ret
33+
st = []
34+
35+
while True:
36+
# 왜 마지막 요소일 때 안나가지고 자꾸 NoneType object has no attribute 'val' 오류 뜸
37+
st.append(head.val)
38+
if head.next is None:
39+
break
40+
head = head.next
41+
42+
while st:
43+
val = st.pop()
44+
node = ListNode(val, None)
45+
ret_head.next = node
46+
ret_head = ret_head.next
47+
48+
return ret.next
49+
50+
# gpt 답변
51+
52+
## 스택 유지
53+
class Solution:
54+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
55+
if not head:
56+
return None
57+
58+
st = []
59+
while head:
60+
st.append(head.val)
61+
head = head.next
62+
63+
dummy = ListNode(0)
64+
current = dummy
65+
66+
while st:
67+
current.next = ListNode(st.pop())
68+
current = current.next
69+
70+
return dummy.next
71+
72+
## 스택 없이 포인터를 뒤집는 방식
73+
class Solution:
74+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
75+
prev = None
76+
current = head
77+
78+
while current:
79+
next_node = current.next
80+
current.next = prev
81+
prev = current
82+
current = next_node
1483

84+
return prev
1585

0 commit comments

Comments
 (0)