Circular Linked Lists - Python

이세진·2022년 4월 3일
0

Computer Science

목록 보기
39/74

생성일: 2021년 11월 3일 오후 8:45

circle.py

class NodeType:
    """ Node Type """
    def __init__(self, item):
        self.info = item
        self.next = None

class CircularLL:
    def __init__(self):
        self.listData = None
        self.length = 0
        self.currentPos = None

    def is_full(self):
        try:
            location = NodeType("test")
            return False
        except:
            return True

    def length_is(self):
        return self.length

    def make_empty(self):
        while self.listData != None:
            tempPtr = self.listData.next
            del self.listData
            self.listData = tempPtr
        self.length = 0

    def find_item(self, listData, item):

        '''[4]'''
        moreToSearch = True
        location = listData.next
        predLoc = listData
        found = False

        while(moreToSearch and not found):
            if (item < location.info):
                moreToSearch = False
            elif(item == location.info):
                found = True
            else:
                predLoc = location
                location = location.next
                moreToSearch = (location != listData.next)
        return location,predLoc
        
    
    def insert_item(self, item):

        '''[5]'''
        newNode = NodeType(item)
        if(self.listData != None):
            location, predLoc = self.find_item(self.listData, item)
            newNode.next = predLoc.next
            predLoc.next = newNode
            if(self.listData.info < item):
                self.listData = newNode
        else:
            self.listData = newNode
            newNode.next = newNode
        self.length += 1

    def delete_item(self, item):

        '''[6]'''
        location, predLoc = self.find_item(self.listData, item)
        if(predLoc == location):
            self.listData = None
        else:
            predLoc.next = location.next
            if(location == self.listData):
                self.listData = predLoc
        del location
        self.length -= 1

   

    def reset_list(self):
        self.currentPos = None

    def get_next_item(self):
        if self.currentPos == None:
            self.currentPos = self.listData
        else:
            self.currentPos = self.currentPos.next
        return self.currentPos.info

    def __str__(self):
        self.reset_list()
        items = []
        for i in range(0, self.length):
            t = self.get_next_item()
            items.append(str(t))
        return " ".join(items)

testcircle.py

from circle import *

if __name__ == '__main__':

    circle = CircularLL()
    
    circle.insert_item(3)
    circle.insert_item(4)
    circle.insert_item(2)
    circle.insert_item(1)
    print(circle)

    circle.delete_item(3)
    circle.delete_item(2)
    print(circle)
profile
나중은 결코 오지 않는다.

0개의 댓글