单链表 Python
时间: 2023-11-19 10:51:13 浏览: 101
好的,以下是 Python 实现单链表的代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addAtHead(self, val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def addAtTail(self, val):
new_node = Node(val)
if not self.head:
self.head = new_node
return
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
def get(self, index):
if index < 0 or not self.head:
return -1
cur = self.head
for i in range(index):
if not cur.next:
return -1
cur = cur.next
return cur.val
def addAtIndex(self, index, val):
if index <= 0:
self.addAtHead(val)
return
cur = self.head
for i in range(index-1):
if not cur:
return
cur = cur.next
new_node = Node(val)
new_node.next = cur.next
cur.next = new_node
def deleteAtIndex(self, index):
if index < 0 or not self.head:
return
if index == 0:
self.head = self.head.next
return
cur = self.head
for i in range(index-1):
if not cur.next:
return
cur = cur.next
if not cur.next:
return
cur.next = cur.next.next
```
阅读全文