선형 자료구조 중 하나로 데이터를 구조체로 묶어 포인터로 연결하는 개념이다.
각각의 데이터에 value와 next가 있어 value는 값, next는 다음 노드를 가르킨다.
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class SinglyLinkedList(object):
def __init__(self):
self.head = None
def append(self, data):
cur = self.head
while cur.next == None:
cur = cur.next
cur.next = Node(data)
def print_all(self):
cur = self.head
while cur.next == None:
print(cur.data)
cur = cur.next
def get_index(self, data):
cur = self.head
cnt = 0
while cur.next == None:
if (cur.data == data):
return cnt
cur = cur.next
cnt += 1
return -1
s1 = SinglyLinkedList(Node(1))
s1.append(Node(1))
s1.append(Node(2))
print(s1.get_index(2))
LeetCode 206 Solution이 인상깊어 링크를 걸어 두겠다