用python 實現連結串列(實現__getitem__,__set__,__len__ 魔法方法)

crystalnsd發表於2017-09-18
'''
用python 實現資料結構--連結串列的實現
'''
class LinkListException(Exception):
    def __init__(self,ex_info):
        self.info = ex_info
        #print(self.info)

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

class LinkList():
    dict = {}
    def __init__(self):
        self._head = None
        self._lenth = 0
    def is_empty(self):
        if self._lenth == 0:
            return True
        else:
            return False
    def __getitem__(self, index):
        if  isinstance(index,int):
            if 0 <= index <self._lenth:
                node = self._getdata(index)
                self.dict[index] = node.data
                return  self.dict[index]
            else:
                raise IndexError
        else:
            raise  LinkListException('index 必須是一個非負整數')
    def __setitem__(self, index, value):
        if  isinstance(index,int):
            if 0 <= index <self._lenth:
                node = self._getdata(index)
                node.data = value
            else:
                raise IndexError
            self.dict[index] = node.data
        else:
            raise  LinkListException('index 必須是一個非負整數')

    def append(self,data):
        if self.is_empty():
            self._head = Node(data)
            self._lenth += 1
        else:
            cus = self._head
            while cus.next:
                cus = cus.next
            cus.next = Node(data)
            self._lenth += 1
    def __len__(self):
        return self._lenth

    def _getdata(self,index):
        cur = self._head
        target = None
        for _ in range(index):
            cur = cur.next
        target = cur
        return target
    def getitems(self):
        items = []
        if self.is_empty():
            return items
        else:
            cur = self._head
            while cur:
                items.append(cur.data)
                cur = cur.next
            return items

    def delete(self,index):
        if self.is_empty():
            raise LinkListException('不能對空連結串列進行刪除操作')
        else:
            if index == 0:
                self._head =  self._head.next
                self._lenth -= 1
            else:
                cur = self._head
                for _ in range(index - 1):
                    cur = cur.next
                cur.next = cur.next.next
                self._lenth -= 1

    def insert(self,index,data):
        if self.is_empty():
            if index == 0:
                self._head = Node(data)
                self._lenth += 1
            else:
                raise LinkListException('只能在空連結串列頭插入資料(index 必須是0')
        else:
            if index == 0:
                node = Node(data)
                node.next = self._head
                node ,self._head = self._head ,node
                self._lenth += 1
            else:
                cur = self._head
                node =Node(data)
                for _ in range(index -1 ):
                    cur = cur.next
                node.next = cur.next
                cur.next = node

測試:

ll = LinkList()

  1. 新增資料:

    ll.append(1)
    ll.append(‘ab’)
    ll.append(‘aabb’)
    ll.append(‘aabbcc’)
    ll[0]
    Out[6]: 1
    ll.getitems()
    Out[5]: [1, ‘ab’, ‘aabb’, ‘aabbcc’]

  2. 變更元素
    ll[1] ,ll[2] = ll[2],ll[1]
    ll.getitems()
    Out[8]: [1, ‘aabb’, ‘ab’, ‘aabbcc’]

  3. 插入資料:
    ll.insert(0,’head’)
    print(len(ll))
    print(ll.getitems())
    ll.insert(1,’2’)
    print(ll.getitems())

5
[‘head’, 1, ‘aabb’, ‘ab’, ‘aabbcc’]
[‘head’, ‘2’, 1, ‘aabb’, ‘ab’, ‘aabbcc’]

相關文章