-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseNodesinkGroup.py
75 lines (71 loc) · 1.81 KB
/
ReverseNodesinkGroup.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
from typing import Optional
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def reverse(begin, end):
previous = begin
begin = end
end = end.next
head = previous
tail = previous.next
while tail != end:
forward = tail.next
tail.next = head
head = tail
tail = forward
previous.next = end
return begin, end, previous
def reverseKGroup(
self, head: Optional[ListNode], k: int
) -> Optional[ListNode]:
tail, tot = head, 0
while tail:
tot += 1
if tot == k:
out = tail
tail = tail.next
if tot < k:
return head
begin, end = head, out
begin, end, previous = Solution.reverse(begin, end)
while 1:
begin = end
tail, tot = end, 0
while tail:
tot += 1
if tot == k:
end = tail
tail = tail.next
if tot < k:
return out
previous.next = end
begin, end, previous = Solution.reverse(begin, end)
def printList(x, flag = 0):
temp = x
tot = 0
while temp:
tot += 1
if flag:
print(temp.val)
temp = temp.next
print(tot, "list")
fin = open("oo.xx", "r")
fout = open("xx.oo", "w")
k = int(fin.readline())
print(k, "intput")
line = [int(x) for x in fin.readline().split(',')]
print(len(line), "input")
head = tail = ListNode()
for x in line:
tail.next = ListNode(x)
tail = tail.next
head = head.next
out = Solution().reverseKGroup(head, k)
tot = 0
while out:
tot += 1
# print(out.val)
fout.write(str(out.val))
out = out.next