1

单链表

单链表是内存地址不连续排列的线性表。单链表每个结点都有两个地址,第一个位置存储数据,第二个位置存储下个结点的内存地址。



class Node(object):
    """单链表结点"""
    def __init__(self, val):
        # _item 存储数据
        self.val = val
        # _next 是下一个结点的标识
        self.next = None # 节点初始状态,不指向任何节点,置空


class SingleList(object):
    """单链表"""
    def __init__(self, node=None):
        self._head = node  # 初始化,不指向任何结点

    def is_empty(self):
        if self._head is None:
            return True
        else:
            return False

    def length(self):
        cur = self._head  # 定义cur,指向第一个结点
        count = 0
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        cur = self._head  # 定义cur,指向第一个结点
        while cur is not None:
            print(cur.val, end=" ")
            cur = cur.next
        print("")

    def add(self, item):
        """链表头部添加元素,头插法"""
        node = Node(item)
        node.next = self._head # node指向首结点
        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):
        """

        :param pos: 从0开始
        :param item: 要添加的节点
        :return:
        """
        if pos <= 0:
            self.add(item)
        elif pos > self.length() - 1:
            self.append(item)
        else:
            pre = self._head  # 首节点
            count = 0
            while count < (pos - 1):
                count += 1
                pre = pre.next
            node = Node(item)
            node.next = pre.next
            pre.next = node

    def remove(self, item):
        """删除数据"""
        cur = self._head
        pre = None
        while cur is not None:
            if cur.val == item:
                if cur == self._head: # 恰好是首节点
                    self._head = cur.next
                else:
                    pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next

    def search(self, item):
        cur = self._head
        while cur is not None:
            if cur.val == item:
                return True
            else:
                cur = cur.next
        return False


if __name__ == '__main__':
    ll = SingleList()
    ll.append(1)
    print(ll.is_empty())
    print(ll.length())

    ll.append(2)
    ll.add(8)
    ll.append(3)
    ll.append(4)
    ll.append(5)
    ll.append(6)
    ll.insert(-1, 9)
    ll.travel()
    ll.insert(3, 100)
    ll.travel()
    ll.insert(10, 200)
    ll.travel()
    ll.remove(200)
    ll.travel()
    ll.remove(9)
    ll.travel()

结果显示:

posted @ 2024-05-27 10:11  Bonne_chance  阅读(7)  评论(0编辑  收藏  举报
1