随笔 - 5  文章 - 0  评论 - 0  阅读 - 533

数据结构与算法学习笔记———链表(Linked List)

链表( Linked List)

# 该篇笔记转自【Python】python链表_小周ipython的博客-CSDN博客_python 链表

简介

链表(Linked List):是一种线性表数据结构。他是用一组任意的存储单元(可以是连续的,也可以是不连续的),来存储一组具有相同类型的数

链表是实现线性表的链式存储结构的基础。

 

单链表每个数据元素占用若干存储单元的组合称为一个链节点,还要存放一个指出这个数据元素在逻辑关系上的直接后继元素所在链节点的地址,该地址称为后继指针。

 

 

双链表(doubly Linked List):链表的一种,也叫做双链表。 它的每个链节点中有两个指针,分别指向直接后继和直接前驱。

 

 

 

 

循环链表(Circualr Linked List):链表的一种。它的最后一个链节点指向头节点,形成一个环。

 

 

 

 

 

链表的python实现:

 

首先定义一个链节点类,然后再定义链表类。 LinkedList类中只有一个链节点变量head用来表示链表的头节点。

 

 

复制代码
class ListNode:
    def __init__(self, val=0 ,next=None):
        self.val = val
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    #add an item to the head of the linked list:
    def insertfront(self,val):
        node = ListNode(val) # first create a node
        node.next = self.head # then let the created node point the head of the original linked list
        self.head = node # At last, the created node be the head of the modified linked list

    # add an item to the end o fhte linked list:
    def inserttail(self,val):
        node = ListNode(val)
        cur = self.head
        while cur.next != None:
            cur = cur.next
        cur.next  = node

    def insertINside(self,val,index):
        node = ListNode(val)
        count = 0
        cur =  self.head
        while cur != None and count < index-1:
            cur = cur.next # firstly, connect the tail of node
            count += 1 # Then, connect the head fo the node

        if cur: return 'error'

        node.next = cur.next
        cur.next = node


    # creat a linked List based on the data(data=[item1,item2,item3....])
    def create(self,data):
        self.head = ListNode(0)
        cur = self.head
        for i in range(len(data)):
            node = ListNode(data[i])
            cur.next = node
            cur = cur.next


    # return the lenth of the linked List
    def length(self):
        count = 0
        cur = self.head
        while cur:
            count += 1
            cur = cur.next
        return count

    def removeFront(self):
        if self.head:
            self.head = self.head.next
    
    def removeinside(self,index):
        count = 0
        cur = self.head
        
        while cur.next and count < index - 1
            count += 1
            cur = cur.next
        
        if not cur:
            return 'Error'
        
        del_node = cur.next
        cur.next = del_node.next
        
复制代码

 

posted on   无甲的乔  阅读(165)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示