单链表------python

单链表的创建、增、删、改、查功能的实现

# -*- codeing = utf-8 -*-
# @Time :2022/3/9 19:29
# @Author : 刘念卿
# @File : 单链表.py
# @Software : PyCharm

# 节点
class Node_l:
    def __init__(self, data):
        # 节点值
        self.data = data
        # 节点的next,指向下一个节点
        self.next = None

    # 查询节点的值  可有可无
    def get_data(self):
        return self.data

# 链表
class Singly_Linked_List:

    def __init__(self):
        # 私有变量 _head
        self._head = None
    # 插入节点
    def head_insert(self, Data):
        """
        头插
        :param data: 插入节点的值
        :return:
        """
        # 创建一个节点
        node = Node_l(Data)
        # 头插
        node.next = self._head
        # 更改_head指向,指向头节点
        self._head = node

    def insert_Tail(self, Data):
        """
        尾插
        :param data:插入节点的值
        :return:
        """
        if  self.Is_Empty():
            # 链表为空,直接插入头部
            self.head_insert(Data)
        else:
            # 链表非空
            node = Node_l(Data)
            cur = self._head
            # 迭代至链表尾部
            while cur.next != None:
                cur = cur.next
            # 尾插
            cur.next = node

    def Is_Empty(self):
        """
        判空
        :return: 空 返回False  否则返回True
        """
        return self._head == None

    def Get_Length(self):
        """
        获取链表长度
        :return:
        """
        if self.Is_Empty():
            return 0
        else:
            cur = self._head
            num = 0
            while cur:
                num += 1
                cur = cur.next
            return num

    def Traversal_Link_List(self):
        """
        遍历单链表
        :return:
        """
        if self.Is_Empty():
            print("链表为空!")
        else:
            cur = self._head
            while cur:
                if cur == self._head:
                    print(cur.data,end=' ')
                    if  not cur.next:
                        print('->',end=' ')
                    else:
                        pass
                else:
                    print("->", cur.data, end=' ')
                cur = cur.next
            print('')

    def Find_item(self, Data):
        """
        查询某个元素是否存在,返回所有的匹配元素下标值
        :param data: 查询的元素值
        :return:
        """
        if self.Is_Empty():
            print("链表为空!")
        else:
            num = []
            n = 0
            cur = self._head
            while cur:
                n += 1
                if cur.data== Data:
                    num.append(n)
                cur = cur.next
            return num

    def Insert_Anywhere(self, Data, pos):
        """
        在任意位置插入元素, pos<0 则插入头部,pos大于链表长度,则插入尾部
        :param data: 节点值
        :param pos:  插入的位置
        :return:
        """
        # 链表为空 或者pos小于等于0 直接头插
        if pos <= 0 or not self.Get_Length():
            self.head_insert(Data)
        #     pos大于等于链表最大值,直接尾插
        elif pos >= self.Get_Length():
            self.insert_Tail(Data)
        #     pos位置合理
        else:
            # 找到pos前一个的位置
            num = 0
            cur = self._head
            while cur and num != pos - 1:
                num += 1
                cur = cur.next
            # 插入节点
            node = Node_l(Data)
            node.next = cur.next
            cur.next = node
	
    def Alter(self, Data, pos):
       """
       修改指定位置的元素
       :param pos:
       :return:
       """
       if self.Is_Empty():
           print("链表为空")
       else:
           if pos in range(1, self.Get_Length() + 1):
               num = 0
               cur = self._head
               while cur and num != pos - 1:
                   num += 1
                   cur = cur.next
               cur.data = Data
           else:
               print("超出范围!")
	
    def Del_and_Re(self, pos):
        """
        删除指定位置的元素并返回
        :return:
        """
        if self.Is_Empty():
            print("链表为空")
        else:
            if pos <= 1 :
                data = self._head.data
                self._head = self._head.next
                return data
            # pos在链表长度范围内
            if pos  in range(2, self.Get_Length()):
                num = 0
                cur = self._head
                while cur and num != pos - 1:
                    num += 1
                    cur = cur.next
                data = cur.next.data
                cur = cur.next.next
                return data
            else:
                print("超出范围!")

if __name__ == '__main__':
    # 创建链表
    List = Singly_Linked_List()
    print(List.Is_Empty())
    List.head_insert(1)
    List.head_insert(2)
    List.insert_Tail(3)
    List.Traversal_Link_List()
    print('length:',List.Get_Length())
    print('return:',List.Del_and_Re(6))
    List.Traversal_Link_List()
    List.Insert_Anywhere(3,6)
    List.Traversal_Link_List()

单链表------python_第1张图片

你可能感兴趣的:(python,数据结构,python,链表)