【数据结构】Python3版本 链表常用操作

 

 1 from collections import deque
 2 
 3 class Test:
 4     def test(self):
 5         # Create an Linkedlist
 6         linkedlist = deque()
 7 
 8         # Add element
 9         # Time Complexity: O(1)
10         linkedlist.append(1)
11         linkedlist.append(2)
12         # [1,2,3]
13         print(linkedlist)
14 
15         # Insert element
16         # Time Complexity: O(N)
17         linkedlist.insert(2, 99)
18         # [1,2,99,3]
19         print(linkedlist)
20 
21         # Access element
22         # Time Comlexity: O(N)
23         element = linkedlist[2]
24         # 99
25         print(element)
26 
27         # Search element
28         # Time Complexity: O(N)
29         index = linkedlist.index(99)
30         # 2
31         print(index)
32 
33         # Update element
34         # Time Complexity: O(N)
35         linkedlist[2] = 88
36         # [1,2,88,3]
37         print(linkedlist)
38 
39         # Remove element
40         # Time Complexity: O(N)
41         # del linkedlist[2] (Delete according to index)
42         linkedlist.remove(88)
43         # [1,2,3]
44         print(linkedlist)
45 
46         # Length
47         # Time Complexity: O(1)
48         length = len(linkedlist)
49         # 3
50         print(length)
51 
52 
53 if __name__ == '__main__':
54     test = Test()
55     test.test()

 

posted @ 2021-01-13 15:54  BTLord小白工作室  阅读(115)  评论(0)    收藏  举报