알고리즘 2(array와 링크드리스트)

allnight5·2022년 11월 8일
0

알고리즘

목록 보기
2/8

생성자란 객체를 생성할때쓰는 함수를 의미한다.

클래스

생성자가되거나 내부에 함수를 만들때 자신을 넘겨주는것을 self 로 표현한다

    class person:
         def __init__(self, param_name):
               self.name = param_name
      

클래스 내부의 함수를 메소드라고 부른다

 def talk(self):
      print("안녕하세요.  제 이름은 ", self.name,  "입니다")

링크드 리스트 구현 - 1

init은 초기화의 의미를 지닌함수로

javascript에서는 사용자가 임의로 선언하는 함수로 다르게 바꿀수있다 initialize()이런식

python에서는 인스턴스 생성시 반드시 처음실행되는 특수함수이며 그순간 데이터의 초기화를 실시하는 함수이다

Node라는 클래스에 인스턴스 함수 생성시 데이터를 넣어주라는 초기화 init을 만들었다

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

3을 가진 Node 를 만드려면 아래와 같이 하면 됩니다!

node = Node(3) 

5와 12를 가진 Node생성

first_node = Node(5) 
second_node = Node(12) 

아래 내요은 first 노드 다음차례로 second_node선언 한내용으로

만약 아래와달리 seconde_node.next = frist_node 로한다면 seconde_node 가 head고 first가 second_node 다음 리스트가된다

first_node.next = second_node

링크드리스트 클래스 생성

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

리스트끝에 링크하여 리스트하나추가

    def append(self, value):
    #cur이라는 지역 변수를 선언하여 지금 링크 위치를 넣어준다
        cur = self.head         
    #while을 이용하여 다음 위치가 None(비어있다 다른말로 다음위치는 없다 존재하지않는다)일때까지 이동시킨다
        while cur.next is not None: 
            cur = cur.next          
        #while문을 통하여 마지막에 추가된 리스트로 왔으니 그다음 주소로해서 내용을 넣어준다
        cur.next = Node(value)

링크드리스트안에 링크된 모든리스트 데이터 출력

    def print_all(self):
    #첫시작인 헤더를 위치로 잡는다
        cur = self.head
        #연결된 리스트가 없을때까지 while을 이용하여 반복시키면 프린트한다
        while cur is not None:
            print(cur.data)
            #다음 리스트로 이동한다
            cur = cur.next 
#링크드리스트 생성자 생성 및 리스트 생성
linked_list = LinkedList(5)
#5-> 12 -> 8  순으로 리스트 생성
linked_list.append(12)
linked_list.append(8)
#현재 링크드리스트안에 data를 전부 보여줌
linked_list.print_all()

링크드 리스트 구현 - 2

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 print_all(self):
        cur = self.head
        while cur is not None:
            print(cur.data)
            cur = cur.next 

#----------------------------------

    #index 노드의 위치로 이동하여 리스트정보를 가져오는함수(메소드) 
    
    def get_node(self, index):
    #헤더부터 타고올라간다
        node = self.head
        #현재 위치를 결정하기위해 선언한변수
        #while을 빠져나오기위한것
        count = 0
        #반복문인 while로 돌면서 head 시작점부터
        #index까지 이동하는것으로 count를 이용하여 빠져나와 위치를 전송해준다
        while count < index:
            node = node.next
            count += 1
        return node  
        #위와 같이 index가아닌 값을 이용해 찾고싶다면
        #while문은 true상태로 돌리고 node = node.next
        #index가아닌 data를 받아와서 
        #if node.data == data:
        #    return node를 해주면 된다
        #하지만 없을경우도 있으니 while을 ture가아닌 node is  not None를 주는것이 좋을것이다
        #큰 단점으로늣 중복값이 있을경우 첫번째 마주한 값에 들어가니 다를조건을 줘야한다
        #새로운 노드 추가
        
   def add_node(self, index, value):
        new_node = Node(value)
        if index == 0:
            new_node.next = self.head.next
            self.head = new_node
            return 
        node = self.get_node(index - 1)
        next_node = node.next
        node.next = new_node
        new_node.next = next_node
        #노드 삭제
	def delete_node(self, index):
        if index == 0:
            self.head = self.head.next
            return
        node = self.get_node(index - 1)
        node.next = node.next.next
    
linked_list = LinkedList(5)
linked_list.append(12)
linked_list.get_node(0) # -> 5를 들고 있는 노드를 반환해야 합니다!

두 링크드리스트의 합

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_linked_list_sum(linked_list_1, linked_list_2):
        sum_1 = _get_linked_list_sum(linked_list_1)
        sum_2 = _get_linked_list_sum(linked_list_2)

        return sum_1 + sum_2

    def _get_linked_list_sum(linked_list):
        sum = 0
        head = linked_list.head
        while head is not None:
            sum = sum * 10 + head.data
            head = head.next
        return sum 


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

linked_list_2 = LinkedList(3)
linked_list_2.append(5)
linked_list_2.append(4)

print(get_linked_list_sum(linked_list_1, linked_list_2))
profile
공부기록하기

0개의 댓글