forked from sammorozov/1337Code_tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206. Reverse Linked List.py
98 lines (61 loc) · 1.83 KB
/
206. Reverse Linked List.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Definition for singly-linked list.
from typing import *
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]:
r_list = []
for i in range(len(head)-1, -1, -1):
value = head[i].val
temp = ListNode(value)
r_list.append(temp)
for j in range(len(r_list)-1):
r_list[j].next = r_list[i+1]
return r_list
def print_linked_list(head: Optional[ListNode]) -> None:
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
mytest = [1, 2, 3, 42]
nodes = []
for i in mytest:
temp = ListNode(i)
nodes.append(temp)
for i in range(len(nodes) - 1):
nodes[i].next = nodes[i + 1]
print_linked_list(Solution().reverseList(nodes))
'''
chat solution
# Definition for singly-linked list.
from typing import *
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]:
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
def print_linked_list(head: Optional[ListNode]) -> None:
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
mytest = [1, 2, 3, 42]
nodes = None
for i in mytest[::-1]: # Reverse the list to build the linked list in the correct order
temp = ListNode(i, nodes)
nodes = temp
print_linked_list(Solution().reverseList(nodes))
'''