본문 바로가기

알고리즘

자료구조

https://youtu.be/BHkIrBeVrWEhttps://youtu.be/ttkVpae9Xz8

상상개발자

 

 

 

REMOVE

 

//첫번째 노드만 지우는 코드이다. 링크드리스트는 첫번째 노드를 살려야 하므로 두번째 노드로 옮겨주는 코드를 다음처럼 한후에 리므브함수를 순환하게 된다.

 

def remove(self, item):

    if self.head.val == item: 

#첫번째 노드인 self.head에 찾는 값(item)이 있다면........  이때 self.head.val은 self.head.val이 가리키는 값이다. 값들끼리 비교한는 것이다.

        self.head = self.head.next 

#self.head를 self.head.next로 옮긴다. 이때 self.head.next는 self.head.next가 가르키는 밸류다. 즉 다음노드이다.

       // 리크드 배열은 첫번째노드가 반드시 있어야 한다. 지우면 안되기에 뒤로 옮겨 놓는다.

 

     else:

         cur = self.head 

# cur를 self.head위로 옮긴다. 첫번째 노드가 지워져서 값이 없으면 cur가 다음 노드

 

 

 

//옮기고 나면 순환에 들어간다.

          while cur.next is not none:  

#순환에 들어가서 첫 번째 노드의 cur.next 변수가 다음 노드와 연결되어 있고...... 

                if cur.val == item: 

# 첫 번째 cur.val변수에  첮는 값이 들어있다면.... 

                    self.removeItem(item)

#리무브함수를 실행하라

                    return

             Print('item does not exist in linked list')

 

 

 

def removeItem(self, item):

    cur = self.head 

# cur를 self.head위로 옮기고 여기서는 첫 번째 노드

    while cur.next is not None:

# cur.next 변수가 다음 두 번째 노드와 연결되 았고

        if cur.next.val == item:

# cur.next변수에 값이 있다면

            nextnod =cur.next.next

# nextnod변수를 만들고 이를 세번째 노드에 있는 cur.next.next 주소로 옮기고.... 

            cur.next =  nextnode

# 첫번째 cur.next 변수를 nextnode 주소지로 옮긴다. 그러면 첫번째 노드가 지워지게 된다. 

 

 

 

 

 

 

//이번에 두번째 노드만 지우는 코드이다.

 

def remove(self, item):

    if self.head.val == item: 

#첫번째 노드인 self.head에 찾는 값이 없다면........

 

      self.head = self.head.next 

 

     else:

         cur = self.head 

# cur를 첫번째 self.head위에 놓는다. 

 

 

 

// 순환에 들어간다.

          while cur.next is not None:  

#순환에 들어가서 첫번째 노드의 cur.next 변수가 다음 노드와 연결되어 있고

                if cur.val == item: 

# 첫 번째 cur.val변수에  값이 들어있다면.... 

                    self.removeItem(item)

#리무브함수를 실행하라

                    return

             Print('item does not exist in linked list')

 

 

 

def removeItem(self, item):

    cur = self.head 

# cur를 self.head위로 옮기고 여기서는 첫번째 노드

    while cur.next is not None:

# cur.next 변수가 다음 노드와 연결되 았다면

        if cur.next.val == item:

# cur.next변수에 값이 있다면

            nextnod =cur.next.next

# nextnod변수를 만들고 이를 cur.next.next 주소로 옮기고 

            cur.next =  nextnode

# 첫번째 cur.next 변수를 nextnode 주소지로 옮긴다. 그러면 첫번째 노드가 지워지게 된다.