做题要用到单链表,就实现了一个静态单链表,别管性能怎么样,能用就行。
为了方便,加入了一些魔法函数,使得它可以像list那样使用索引功能切片功能和for循环。
链表的node是一个二元的list,第一个元素是数据,第二个元素是下一个node的下标。
链表可以自动增长长度,一开始是8,每次翻一倍。
链表内部的那个list的头两个节点分别是空闲头结点和非空闲头结点。
向链表里增加数据有很多种方法,在示例里演示了4种,就是这一行的四种方法。
依次是初始化,函数,头插,尾添。
LinkList([7, 8])(range(3)).insert(6).append(5)
但实际上只有两个,一个头插,一个尾添。初始化和函数都是调用的append,所以都是尾添。
另外还可以使用赋值来增加新元素,但是没有实现完该功能,目前只能给某一个节点赋值。
删除也是没有实现完,只能删除某一个节点,如del ll[4]这样。
代码如下
# -*- coding: cp936 -*-
'''
这是一个静态单链表的实现
同时实现了一些magic method用于进行iter或者slice等等
需要注意的是,代码中的游标(指针)和key不是同一个概念
cur(pointer)是这个静态链表元素的实际下标
key是这个单链表元素的逻辑下标
未完,以后再写吧,写了一上午了,有些懒
2017.03.10
平善明
'''
class LinkList():
# a linklist implement by list with static
# 2017.03.10
# psm
def __init__(self, li=[]):
self.size = 10 # the real size of ll
self.li = [[None, i + 1] for i in range(self.size)] # allocate
self.li[self.size - 1][1] = None # the tail point None
self.li[0][0] = self.size - 2 # the length of unused space
self.li[0][1] = 2 # the pointer to the first unused space
self.li[1][0] = 0 # the length of ll(used space)
self.li[1][1] = None # the pointer to the first used space
if li != []: # add the items to the ll
self(li)
def insert(self, x):
# insert x at the begining of the LinkList
if self.li[0][0] < 1:
self.expandSize() # if no space,expand the ll
nullCur = self.li[0][1] # the pointer to the first unused space
self.li[0][0] -= 1 # unused space minus one
self.li[1][0] += 1 # used space add one
self.li[0][1] = self.li[nullCur][1] # move unused pointer
self.li[nullCur][0] = x