python数据结构之链表

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
''''
链表的实现,单向链表
'''
 
'''建立节点'''
class jd:
    def __init__(self,data):
        self.data = data
        self.next = None
 
'''实现链表的关系'''
class Linklist:
    def __init__(self,jd2):
        self.head = jd2
        self.head.next = None
        self.tail = self.head
 
    def add(self,jd2):
        self.tail.next = jd2
        self.tail = self.tail.next
 
    def view(self):
        jd2 = self.head
        linkstr = ""
        while jd2 is not None:
            if jd2.next is not None:
                linkstr = linkstr+str(jd2.data)+"-->"
            else:
                linkstr+=str(jd2.data)
            jd2 = jd2.next
        print(linkstr)
 
if __name__ == "__main__":
    jd1 = jd(67)
    jd2 = jd(78)
    jd3 = jd(46)
    jd4 = jd(19)
 
    '''节点1(jd1)作为表头'''
    lb = Linklist(jd1)
 
    '''jd2作为第二个节点'''
    lb.add(jd2)
    lb.add(jd3)
    lb.add(jd4)
 
    '''遍历这个链表'''
    lb.view()

以上代码实现的链表如下图:

python数据结构之链表

执行结果如下图:

python数据结构之链表


本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1896277