python数据结构与算法——链表

具体的数据结构可以参考下面的这两篇博客:

python 数据结构之单链表的实现

http://www.cnblogs.com/yupeng/p/3413763.html

python 数据结构之双向链表的实现

http://www.cnblogs.com/yupeng/p/3413800.html

我这里只实现了单链表的类型,代码也相对精简一点:

先构造关于节点的类:

1 class Node:
2     def __init__(self,data=None,next=None):
3         self.data = data
4         self.next = next

节点只有两个成员,一个是节点的数据,一个是链表的键值,用于查找其中的元素,另一个是指向下一个结点的引用。

通过结点,下面实现了链表的类,提供了在链表的两种插入和删除方法

 1 class Chain:
 2     def __init__(self):
 3         self.head = None
 4         self.tail = None
 5         self.count = 0
 6         
 7     def append(self,node):
 8         """ 在链表末尾追加元素 """
 9         self.count += 1
10         if self.head == None:
11             self.head = node
12             self.tail = self.head
13         else:
14             self.tail.next = node
15             self.tail = self.tail.next
16  
17     def __repr__(self):
18         """ 重构:对链表进行输出 """
19         temp = self.head
20         cstr = ""
21         for i in range(self.count-1):
22             cstr += str(temp.data)+' -> '
23             temp = temp.next
24         cstr += str(temp.data)
25         return cstr
26 
27     def insert(self,n):
28         """ 在一个有序链表中插入元素
29             输入 元素的data值
30         """
31         self.count += 1
32         t = self.head   # 暂存头指针,并非其引用
33         p = Node(n)
34         if t.data > n:
35             p.next = t      # 可以写成 p.next = self.head
36             self.head = p   # 不能写成 t=p
37         else:
38             while t!=None:
39                 if t.next==None or t.next.data > n:
40                     p.next = t.next     # 保存后面的节点
41                     t.next = p
42                     break
43                 t = t.next
44     
45     def delete(self,data):
46         """ 删除链表中指定元素
47             输入 原素的data值
48             备注: 如果有多个同样的元素,一次只删除一个
49         """
50         t = self.head           # 从头结点开始查找,用于缓存当前结点的父结点
51         if self.head.data==data:
52             self.head = self.head.next
53             self.count -= 1
54             return True
55 
56         while t.next!=None:
57             if t.next.data==data:    # 找到目标结点为下一个结点
58                 # 意味着必然存在下下个结点
59                 t.next = t.next.next # 将当前结点的下一个结点直向下下个结点
60                 self.count -= 1
61                 return True
62             else:
63                 t = t.next    # 继续找下下个结点
64         else:
65             # while-else结构,当while循环没有碰到break时,调用else语句
66             # 找不到数据
67             return False

测试结果:

if __name__=="__main__":
    L = [1,2,3,4,5]
    chain = Chain()
    for i in L:
        n = Node(i)
        chain.append(n)
    
    chain.insert(0)
    print chain
>>> 0 -> 1 -> 2 -> 3 -> 4 -> 5
    
    chain.delete(3)     # 删除中间数据
    print chain
>>> 0 -> 1 -> 2 -> 4 -> 5

    chain.delete(0)     # 删除头数据
    print chain
>>> 1 -> 2 -> 4 -> 5

    chain.delete(5)     # 删除尾数据
    print chain
>>> 1 -> 2 -> 4
原文地址:https://www.cnblogs.com/hanahimi/p/4692476.html