-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcircularlinkedlist.py
64 lines (44 loc) · 1.58 KB
/
circularlinkedlist.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
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
newNode = Node(insertVal)
if not head:
newNode.next = newNode
return newNode
prev = head
node = head.next
while node:
if prev.val > node.val and (insertVal < node.val or insertVal > prev.val):
break
if prev.val <= insertVal <= node.val:
break
if node == head:
break
prev = node
node = node.next
prev.next = newNode
newNode.next = node
return head
def insert(self, head: 'Node', insertVal: int) -> 'Node':
insertNode = Node(insertVal)
if head is None:
insertNode.next = insertNode
return insertNode
node = head
while node:
if node.next.val < node.val and (insertVal <= node.next.val or insertVal > node.val):
break
if node.val <= insertVal <= node.next.val:
break
elif node.next == head:
break
node = node.next
insertNode.next = node.next
node.next = insertNode
return head