항해99 - 3주차, 삽입 정렬 리스트

Jang Seok Woo·2022년 1월 30일
0

알고리즘

목록 보기
45/74

Today I learned
2022/01/29

회고록


1/29

항해 99, 알고리즘 2주차

교재 : 파이썬 알고리즘 인터뷰

정렬(Sort)

1. 이론

버블정렬

링크텍스트

선택정렬

링크텍스트

삽입정렬

링크텍스트

2. 문제

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/

3. MySol

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}')

4. 배운 점

  • 노드를 이해하려고 접근시 기존 배열이나 변수에 접근하는 것과 상당히 다르고 하나 하나 참조식으로 따라가는 것이 매우 어렵다.
  • 그림을 그려 따라가 볼것

5. 총평

노드와 친숙해지는 시간

profile
https://github.com/jsw4215

0개의 댓글