Given a singly-linked list, where each node contains an integer value, sort it in ascending order. The selectoin sort algorithm should be used to solve this problem.
Examples
null, is sorted to null
1 -> null, is sorted to 1 -> null
1 -> 2 -> 3 -> null, is sorted to 1 -> 2 -> 3 -> null
4 -> 2 -> 6 -> -3 -> 5 -> null, is sorted to 2 -> 3 -> 4 -> 5 -> 6
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# write your solution here
class Solution(object):
def selectionSort(self, head):
if head is None:
return None
dummy = ListNode(0)
dummy.next = head
min_node = ListNode(None)
while head is not None:
min_node = self.find_min(head)
self.swap_val(head,min_node)
head = head.next
return dummy.next
"""
input: ListNode head
return: ListNode
"""
# write your solution here
def find_min(self,head):
min_node = ListNode(500)
while head is not None:
if head.val < min_node.val:
min_node = head
head = head.next
return min_node
def swap_val(self,node1,node2):
node1.val,node2.val = node2.val,node1.val
网友评论