思路源于Learn more python in hard way一书的Exercise 13: Single Linked Lists一节;
效率应该比较低,就是为了练练脑而已;
测试也是最基础的测试,使用nosetests与pycharm。
把要实现的功能列出来
- 链表的基本结构,即节点;
- 增删读改,看了看书中的思路,发现“改”是空缺的。
功能 | 函数名 |
---|---|
节点 | __init__(self, value, nxt) |
打印节点 | __repr__(self) |
在末尾插入 | push(self, obj) |
在开始插入 | shift(self, obj) |
删除末尾一项 | pop(self) |
删除开始一项 | unshift(self) |
删除匹配项 | remove(self, obj) |
读取(不移除,下同)第一项 | first(self) |
读取最后一项 | last(self) |
读取链表长度 | count(self) |
读取第index + 1项 | get(self, index) |
打印链表 | dump(self, mark=None) |
写出类的框架
节点
class SingleLinkedListNode(object): def __init__(self, value, nxt): self.value = value self.next = nxt def __repr__(self): nval = self.next and self.next.value or None return f"[{self.value}:{repr(nval)}]"
增删读改
class SingleLinkedList(object): def __init__(self): self.begin = None self.end = None def push(self, obj): """Appends a new value on the end of the list.""" def pop(self): """Removes the last item and returns it.""" def shift(self, obj): """Another name for push.""" def unshift(self): """Removes the first item and returns it.""" def remove(self, obj): """Finds a matching item and removes it from the list.""" def first(self): """Returns a *reference* to the first item, does not remove.""" def last(self): """Returns a reference to the last item, does not remove.""" def count(self): """Counts the number of elements in the list.""" def get(self, index): """Get the value at index.""" def dump(self, mark=None): """Debugging function that dumps the contents of the list."""
链表测试
sllist_test.py
from .sllist import * # from ex13chao import * def test_push(): colors = SingleLinkedList() colors.push("Pthalo Blue") assert colors.count() == 1