Today I learned
2022/01/29
회고록
항해 99, 알고리즘 2주차
교재 : 파이썬 알고리즘 인터뷰
정렬(Sort)
버블정렬
선택정렬
삽입정렬
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
https://leetcode.com/problems/insertion-sort-list/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertionSort(head):
cur = parent = ListNode(None)
while head:
while cur.next and cur.next.val < head.val:
cur = cur.next
cur.next,head.next,head = head,cur.next,head.next
cur = parent
return cur.next
if __name__ == '__main__':
dummy = [4,2,1,3]
for i in reversed(range(len(dummy))):
if i+1 != len(dummy):
node = ListNode(dummy[i],node)
else:
node = ListNode(i, None)
sorted = insertionSort(node)
print(f'{sorted}')
노드와 친숙해지는 시간