python_链表 数组

Task01

数组

  • 实现一个支持动态扩容的数组
  • 实现一个大小固定的有序数组,支持动态增删改操作
  • 实现两个有序数组合并为一个有序数组

链表

  • 实现单链表、循环链表、双向链表,支持增删操作
  • 实现单链表反转
  • 实现两个有序的链表合并为一个有序链表

数组实现如下:

class MyArr:

    def __init__(self, *args, size=None, fixed_size=False):
        # args : 可指定数组    size : 数组大小   fixed_size : 是否固定数组长度
        if not isinstance(fixed_size,  bool):
            raise TypeError("Fixed_size must be bool")

        self.fixed = fixed_size

        if args:
            self._data = [i for i in args]
            if size < len(args):
                raise IOError("Size shouldn't be less than the length of args")
            else:
                if not isinstance(size, int):
                    raise TypeError("List length must be integer")
                self.is_empty = False
                self._size = size
                none_size = [None] * (self._size - self.length(self._data))
                self._data += none_size
        else:
            if self.fixed:
                if not size:
                    raise IOError("For fixed array,size can't be none")
                else:
                    if not isinstance(size, int):
                        raise TypeError("List length must be integer")
                    self.is_empty = True
                    self._size = size
                    self._data = [None] * self._size
            else:
                if not size:
                    self.is_empty = True
                    self._size = 0
                    self._data = [None] * self._size
                else:
                    if not isinstance(size, int):
                        raise TypeError("List length must be integer")
                    self.is_empty = True
                    self._size = size
                    self._data = [None] * self._size

    def __str__(self):
        str_res = """
        Array: {array}
            empty: {empty}
            length: {length}
        """.format(array=self._data, empty=self.is_empty, length=self._size)
        return str_res

    @staticmethod
    def length(args):
        count = 0
        for data in args:
            if data:
                count += 1
        return count

    @staticmethod
    def sort(args):
        for i in range(1, len(args)):
            count = 0
            base = args[i-1]
            for data in args[i:]:
                count += 1
                if data is not None:
                    if base > data:
                        c = data
                        args[count] = base
                        args[count-1] = c
                    else:
                        base = data
                else:
                    raise TypeError("None_type can't be sorted")

    def insert(self, index, value):
        # index : 插入位置  value : 插入数值
        if not isinstance(index, int):
            raise TypeError("Index must be integer")
        if self.is_empty:
            if self.fixed and index + 1 > self._size:
                raise IOError("Fixed array is not as long as you think")
            elif self.fixed and index + 1 <= self._size:
                self._data[index] = value
                self.is_empty = False
            elif not self.fixed and index + 1 > self._size:
                self._data = [None] * (index + 1)
                self._data[index] = value
                self._size = index + 1
                self.is_empty = False
            else:
                self._data[index] = value
                self.is_empty = False
        else:
            if self.fixed:
                if (index + 1 > self._size) or (self.length(self._data) == self._size):
                    raise IOError("Fixed array is not as long as you think")
                else:
                    leng = self.length(self._data)
                    for i in range(1, leng - index + 2, 1):
                        self._data[leng-i+1] = self._data[leng-i]
                    self._data[index] = value
            else:
                if index + 1 > self._size:
                    self._data += [None] * (index + 1 - self._size)
                    self._data[index] = value
                    self._size += 1
                else:
                    if self.length(self._data) == self._size:
                        self._data += [None]
                        for i in range(1, self.length(self._data) - index, 1):
                            self._data[self.length(self._data) - i] = self._data[self.length(self._data) - i - 1]
                        self._data[index] = value
                        self._size += 1
                    else:
                        for i in range(1, self.length(self._data) - index, 1):
                            self._data[self.length(self._data) - i] = self._data[self.length(self._data) - i - 1]
                        self._data[index] = value

    def append(self, *args):
        # args:待合并数组
        if self.fixed:
            raise IOError("The array is fixed,please use insert")
        else:
            self._data += args
            self._data.sort()
            print("1")
            self._size += self.length(args)
            self.is_empty = False

    def delete(self, index):
        # index:需删除元素索引
        if index > self.length(self._data):
            raise TypeError("No element here")
        else:
            if self.is_empty:
                raise IOError("The array is empty")
            else:
                leng = self.length(self._data)
                for i in range(1, leng - index, 1):
                    self._data[index + i - 1] = self._data[index + i]
                self._data[leng-1] = None
                self._size -= 1
            if self.length(self._data) == 0:
                self.is_empty = True

    def update(self, index, value):
        # index:更新元素索引 value:更新元素值
        if not isinstance(index, int):
            raise TypeError("Index must be integer")
        if self.is_empty:
            raise IOError("The array is empty")
        else:
            if not self._size > index:
                raise IndexError("Index be not more than array length")
            else:
                self._data[index] = value


if __name__ == '__main__':
    array = MyArr(1, 2, size=5, fixed_size=True)
    print(array)
    array.insert(2, 5)
    print(array)
    try:
        array.append(3, 4, 1)
        print(array)
    except Exception as e:
        print('append:', e)
    array.update(2, 9)
    print(array)

链表实现如下

class Node(object):

    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingleLinkList(object):
    """单链表"""

    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        return self.__head is None

    def length(self):
        cur = self.__head
        count = 0
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def add(self, item):
        # 头部插入
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def append(self, item):
        # 尾部插入
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            cur.next = node

    def insert(self, pos, item):
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            while count < (pos - 1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node

    def delete(self, item):
        pre = self.__head
        if pre is None:
            return False
        elif pre.elem == item:
            self.__head = pre.next
            return True
        else:
            while pre.next is not None:
                if pre.next.elem == item:
                    pre.next = pre.next.next
                    return True
                else:
                    pre = pre.next
            return False
class Node(object):

    def __init__(self, item):
        self.elem = item
        self.next = None
        self.prev = None


class DoubleLinkList(object):
    """双向链表"""

    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        return self.__head is None

    def length(self):
        cur = self.__head
        count = 0
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def append(self, item):
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def add(self, item):
        node = Node(item)
        node.next = self.__head
        self.__head = node
        node.next.prev = node

    def insert(self, pos, item):
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            cur = self.__head
            counter = 0
            while counter is not pos:
                counter += 1
                cur = cur.next
            node = Node(item)
            node.prev = cur.prev
            cur.prev.next = node
            node.next = cur
            cur.prev = node

    def delete(self, item):
        cur = self.__head
        while cur is not None:
            if cur.elem == item:
                if cur == self.__head:
                    self.__head = cur.next
                    if cur.next is not None:
                        cur.next.prev = None
                else:
                    cur.prev.next = cur.next
                    if cur.next is not None:
                        cur.next.prev = cur.prev
                return True
            else:
                cur = cur.next
        return False

class Node(object):

    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingleLinkList(object):
    """单向循环链表"""

    def __init__(self, node=None):
        self.__head = node
        if node is not None:
            node.next = node

    def is_empty(self):
        return self.__head is None

    def length(self):
        if self.is_empty():
            return 0
        cur = self.__head
        count = 1
        while cur.next != self.__head:
            count += 1
            cur = cur.next
        return count

    def add(self, item):
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = self.__head

        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next
            node.next = self.__head
            self.__head = node
            cur.next = node

    def append(self, item):
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = node
        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next
            cur.next = node
            node.next = self.__head

    def insert(self, pos, item):
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            while count < (pos - 1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node

    def delete(self, item):
        pre = self.__head
        cur = self.__head
        if cur is None:
            return False
        elif cur.elem == item:
            if cur.next == self.__head:
                self.__head = None
                return True
            else:
                while pre.next != self.__head:
                    pre = pre.next
                self.__head = cur.next
                pre.next = self.__head
                return True
        else:
            while pre.next != self.__head:
                if pre.next.elem == item:
                    pre.next = pre.next.next
                    return True
                else:
                    pre = pre.next
            return False


    def rev(SingleLinkList):
    	# 单链表的反转
        pre = SingleLinkList
        cur = SingleLinkList.next
        pre.next = None
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

你可能感兴趣的:(数据结构_python)