[python] Linked List

Joey Hong·2020년 12월 21일
0

Python

목록 보기
1/2

geeksforgeeks python Linked List

함수

  • 노드 생성 함수
    • data에 값 저장
    • next에 다음 노드 연결
class Node:
    # Function to initialize the node object 
    def __init__(self, data): 
        self.data = data  # Assign data 
        self.next = None  # Initialize next as null 
  • Linked List 생성 함수
    • 링크드 리스트의 시작(head) 생성
# Linked List class 
class LinkedList: 
     
    # Function to initialize the Linked  
    # List object 
    def __init__(self):  
        self.head = None

생성

  • Linked List 생성
    • 아무것도 저장되지 않은 head도 생성됨
# llist라는 Linked List 생성
llist = LinkedList()
  • Linked List의 head를 Node로 초기화
    • data가 1인 Node를 생성해서 head로 지정
# Linked List의 시작은 값이 1인 Node
llist.head = Node(1)
  • 연결할 Node 추가적으로 생성
# 값이 각각 2와 3인 노드 생성
second = Node(2)
third = Node(3)
  • 추가 Node들을 Linked List에 연결
# Linked List의 시작에 second 노드 연결
llist.head.next = second
# second 노드에 third 연결
second.next = third
  • Linked List data 출력
    • temp를 리스트의 head Node로 초기화
    • temp를 매번 다음 Node로 변경
    • temp가, 즉 Node가 존재하는 한 출력 진행
    • temp에 담긴 Node의 data 출력
temp = llist.head
while(temp):		#temp에 노드가 있는한
    print(temp.data)	#노드의 data 출력
    temp = temp.next

# 1
# 2
# 3
profile
개발기록

0개의 댓글