数据结构学习--单链表(python)

概念

链表(linked_list)是物理存储单元上非连续的、非顺序的存储结构,数据元素的逻辑顺序
是通过链表的指针地址实现,每个元素包含两个结点,一个是存储元素的数据域 (内存空间)
,另一个是指向下一个结点地址的指针域。根据指针的指向,链表能形成不同的结构,例如
单链表,双向链表,循环链表等.
链表通过将链点 i 与其邻居链点 i+1 通过指针相关联,从索引 0 到索引 N-1 对链点进
行排序.

实现

class Node:
    """
    链点
    """

    def __init__(self, data):
        self.data = data    # 数据域
        self.next = None    # 指针域

class SingleLinkedList:
    """
    单链表
    """

    def __init__(self, head=None):
        self.head = Node(head)    # 链表头部元素
        self._length = None

    # 向链表中添加新链点
    def append(self, value):
        self._length = None
        new_node = Node(value)
        # 将头部节点指向临时变量
        current = self.head
        # 当头部节点存在时
        if self.head:
            # 循环遍历到链表的最后一个节点
            while current.next:
                current = current.next
            current.next = new_node
        # 当头部节点不存在时
        else:
            self.head = new_node

    # 判断链表是否为空
    def is_empty(self):
        return bool(self.head)

    # 向链表任意位置插入元素
    def insert(self, position, value):
        self._length = None
        new_node = Node(value)
        # 判断插入位置是否在链表的索引范围内
        if position < 0 or position > self.get_length():
            raise IndexError('Out of linked list range.')

        # 当插入位置为头节点时
        if position == 0:
            new_node.next, self.head = self.head, new_node
            return
        # 当插入位置不在头节点时,遍历链表找到插入位置,插入新节点
        current = self.head
        i = 0
        while i < position:
            pre, current = current, current.next
            i += 1
        pre.next, new_node.next = new_node, current

    # 删除指定位置的节点
    def remove(self, position):
        self._length = None
        # 判断删除位置是否在链表的索引范围内
        if position < 0 or position > self.get_length() - 1:
            raise IndexError('Position out of linked list range.')

        i = 0
        current = self.head
        # 当删除位置为头节点时
        if position == i:
            self.head, current.next = self.head.next, None
            return

        # 当删除位置不是头节点时,遍历链表找到删除位置
        i += 1
        prev, current = current, current.next
        while i != position:
            prev, current = current, current.next
            i += 1
        prev.next, current.next = current.next, None

    # 获取链表长度
    def get_length(self):
        if self._length is not None:
            return self._length
        current = self.head
        length = 0
        while current is not None:
            length += 1
            current = current.next
        self._length = length
        return length

    # 遍历链表,并依次打印节点数据
    def print_list(self):
        print('linked_list:')
        current = self.head
        while current is not None:
            print(current.data)
            current = current.next

    # 将链表反转
    def reverse(self):
        prev = None
        current = self.head
        while current is not None:
            # next_node = current.next
            # current.next = prev
            # prev = current
            # current = next_node
            next_node, current.next = current.next, prev
            prev, current = current, next_node
        self.head = prev

    # 将列表转换为链表
    def init_list(self, data_list):
        self.head = Node(data_list[0])
        current = self.head
        for item in data_list[1:]:
            node = Node(item)
            current.next, current = node, node

    # 替换指定位置的节点
    def replace(self, position, value):
        # 判断替换位置是否在链表索引范围内
        if position < 0 or position > self.get_length() - 1:
            raise IndexError("Position out of linked-list range.")
        _node = Node(value)
        _current = self.head
        i = 0
        if position == 0:
            _node.next, self.head = self.head.next, _node
            _current.next = None
        else:
            i += 1
            _prev, _current = _current, _current.next
            while i != position:
                i += 1
                _prev, _current = _current, _current.next
            _prev.next, _node.next = _node, _current.next
            _current.next = None

    # 返回给定值的第一个节点索引
    def index(self, value):
        _current = self.head
        i = 0
        while _current is not None:
            if _current.data == value:
                return i
            i += 1
            _current = _current.next
        return -1

    def __getitem__(self, position):
        if position < 0 or position > self.get_length() - 1:
            raise IndexError("Position out of linked-list range.")
        _current = self.head
        i = 0
        while i != position:
            _current = _current.next
            i += 1
        return _current.data

原文地址:https://www.cnblogs.com/thunderLL/p/12034558.html

时间: 2024-07-31 22:33:07

数据结构学习--单链表(python)的相关文章

数据结构学习--单循环链表(python)

概念 将单链表的终端节点的指针由原来的空指针改为指向头节点, 就是整个单链表形成一个环, 这种首尾相接的单链表称为单循环链表. 实现 class Node: """ 节点 """ def __init__(self, value): self.data = value self.next = None class CircularLinkedList: def __init__(self): self.rear = None # 尾节点 def

C#数据结构-单链表

理论基础: 链表是用一组任意的存储单元来存储线性表中的数据元素. 如果结点的引用域只存储该结点直接后继结点的存储地址,则该链表叫单链表(Singly Linked List). 单链表由头引用H唯一确定.头引用指向单链表的第一个结点,也就是把单链表第一个结点的地址放在H中. C#实现: 1接口 引用线性表的接口IListDS<T> 2实现 首先,必须定义一个单链表的节点类.  1 public class Node<T> 2    { 3        private T data

数据结构:单链表结构字符串(python版)

1 #!/urs/bin/env python 2 # -*- coding:utf-8 -*- 3 4 #异常类 5 class stringTypeError(TypeError): 6 pass 7 8 #节点类 9 class Node(object): 10 def __init__(self, elem, next_ = None): 11 self.elem = elem 12 self.next = next_ 13 #单链表类 14 class single_list(obje

数据结构:单链表结构字符串(python版)添加了三个新功能

1 #!/urs/bin/env python 2 # -*- coding:utf-8 -*- 3 4 #异常类 5 class stringTypeError(TypeError): 6 pass 7 8 #节点类 9 class Node(object): 10 def __init__(self, elem, next_ = None): 11 self.elem = elem 12 self.next = next_ 13 #单链表类 14 class single_list(obje

python数据结构之单链表

单链表的操作 1.is_empty()链表是否为空 2.length()链表的长度 3.add()链表的头部添加元素 4.append()链表尾部添加元素 5.insert()指定位置添加元素 6.remove()删除节点 7.search()查找链表是否存在 源代码 class Node(): """节点""" def __init__(self,data = None): self.elem = data #节点中的数据 self.next

数据结构(一) 单链表的实现-JAVA

数据结构还是很重要的,就算不是那种很牛逼的,但起码得知道基础的东西,这一系列就算是复习一下以前学过的数据结构和填补自己在这一块的知识的空缺.加油.珍惜校园中自由学习的时光.按照链表.栈.队列.排序.数组.树这种顺序来学习数据结构这门课程把. -WH 一.单链表的概念 链表是最基本的数据结构,其存储的你原理图如下图所示 上面展示的是一个单链表的存储原理图,简单易懂,head为头节点,他不存放任何的数据,只是充当一个指向链表中真正存放数据的第一个节点的作用,而每个节点中都有一个next引用,指向下一

数据结构之单链表(C++实现)

有一段时间没有写一些关于数据结构的程序了,正好算法导论这门课学到红黑树,感觉数据结构都忘得差不多了,而且考研还要考,故再拿来复习一下. 一.C++实现单链表 #include<iostream> using namespace std; typedef struct LNode { int data; struct LNode *next; }LNode,*LinkList; void CreateList_L(LinkList &L, int n) { L = new LNode()

数据结构之——单链表

今天闲来无事,就打算把大一的时候写过的数据结构重温一遍,基本上我在大一之后只在单片机上用过几次顺序表和循环队列之外再就很少使用过数据结构了. 并且乘着写一下数据结构也可以熟悉熟悉vim. 首先定义单链表节点: 1 #define DataType int 2 3 struct node{ 4 DataType data; 5 struct node *next; 6 }; 7 struct node list,*p_list; 单链表这个数据结构需要一些函数来对她操作,一般需要有这些: 1.初始

数据结构学习之链表(单向、单循环以及双向)(递归实现)

1.链表优点 相比较普通的线性结构,链表结构的优势是什么呢?我们可以总结一下: (1)单个节点创建非常方便,普通的线性内存通常在创建的时候就需要设定数据的大小 (2)节点的删除非常方便,不需要像线性结构那样移动剩下的数据 (3)节点的访问方便,可以通过循环或者递归的方法访问到任意数据,但是平均的访问效率低于线性表 那么在实际应用中,链表是怎么设计的呢?我们可以以int数据类型作为基础,设计一个简单的int链表: 2.单向链表 (1)设计链表的数据结构 typedef struct _LINK_N