# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insert(self, head, value):
"""
input: ListNode head, int value
return: ListNode
"""
# write your solution here
new_node = ListNode(value)
# empty list
if (head == None):
head = new_node
return head
# one element list
elif (head.next == None):
if (head.val >= value):
# insert before head
new_node.next = head
head = new_node
return head
else:
# insert after head
head.next = new_node
return head
# at least two elements in list
else:
prev = head
curr = head
while(curr != None):
if (curr.val < value):
prev = curr
curr = curr.next
else:
break
# now curr.val > value and prev.val <= value. Insert the node between prev and curr
prev.next = new_node
new_node.next = curr
return head
20180826: there is a bug don't know where.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.