链表( 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
标签:node,head,cur,self,List,next,链表,Linked From: https://www.cnblogs.com/wujiadeqiao/p/16657626.html