-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206_reverseLinkedList.py
43 lines (32 loc) · 964 Bytes
/
206_reverseLinkedList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 206. Reverse Linked List
# 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: ListNode) -> ListNode:
prev = None
while head:
next_node = head.next
head.next = prev
prev = head
head = next_node
return prev
'''
stack = deque()
if not head:
return head
while(head):
stack.appendleft(head.val)
head = head.next
val = stack.popleft()
dummy_node = ListNode(val)
head = dummy_node
while(stack):
val = stack.popleft()
dummy = ListNode(val)
head.next = dummy
head = head.next
return dummy_node
'''