-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_linkedlist.py
72 lines (57 loc) · 1.61 KB
/
create_linkedlist.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 链表节点类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 链表类
class LinkedList:
def __init__(self):
self.head = None
def addAtHead(self, val: int) -> None:
self.head = ListNode(val, self.head)
def addAtTail(self, val: int) -> None:
if not self.head:
self.head = ListNode(val)
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = ListNode(val)
def deleteAtIndex(self, index: int) -> None:
if not self.head:
return
if index == 0:
self.head = self.head.next
else:
cur = self.head
for i in range(index - 1):
cur = cur.next
if not cur:
return
if not cur.next:
return
cur.next = cur.next.next
def get(self, index: int) -> int:
if not self.head:
return -1
cur = self.head
for i in range(index):
cur = cur.next
if not cur:
return -1
return cur.val
# 创建一个链表
# 创建一个链表
l = LinkedList()
# 向链表头部添加节点
l.addAtHead(1)
# 向链表尾部添加节点
l.addAtTail(2)
# 获取链表中第一个节点的值
print(l.get(0)) # 输出 1
# 获取链表中第二个节点的值
print(l.get(1)) # 输出 2
# 删除链表中第二个节点
l.deleteAtIndex(1)
# 获取链表中第二个节点的值
print(l.get(1)) # 输出 -1,因为第二个节点已经被删除了