스파르탄 365 2주차 (1) - k번째

류지연·2021년 5월 4일
0
post-thumbnail

1. 문제링크

https://online.spartacodingclub.kr/enrolleds/606a6494ca5c2e219f9ca31e/ehomeworks/606a6494ca5c2e219f9ca352

2. 풀이 생각

  • k번째 노드를 가져와서 수를 구해야 겠다.
  • 뒤에서 몇번째인가
  • 다른 노드보다 k만큼 떨어지게

3. 풀이


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self, value):
        self.head = Node(value)

    def append(self, value):
        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = Node(value)

    def get_kth_node_from_last(self, k):
       length = 1
       cur = self.head

       while cur.next is not None:
           cur = cur.next
           length += 1
       end_length = length - k
       cur = self.head
       for i in range(end_length):
           cur = cur.next
       return cur



linked_list = LinkedList(6)
linked_list.append(7)
linked_list.append(8)

print(linked_list.get_kth_node_from_last(2).data)

4. 소감

문제를 풀기에 앞서 해결하기 위한 방법에 대한 색다른 생각이 필요할 것 같다.
시간복잡도를 확인해보니 생각과는 다르게 큰 변화가 없었다.
문법에 대하여 다시 정리해보아야 겠다.

profile
개발자

0개의 댓글