python往单链表中写入数据
时间: 2023-09-07 07:17:34 浏览: 57
要往单链表中写入数据,你需要先定义链表的节点类,然后实现一个链表类,包含插入节点、删除节点、遍历节点等方法。
下面是一个简单的单链表实现,包含节点类和链表类:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
current = self.head
while current.next:
current = current.next
current.next = Node(data, None)
def insert_at_index(self, index, data):
if index < 0 or index > self.get_length():
raise Exception("Invalid index")
if index == 0:
self.insert_at_beginning(data)
return
current = self.head
current_index = 0
while current:
if current_index == index - 1:
node = Node(data, current.next)
current.next = node
break
current = current.next
current_index += 1
def delete_at_index(self, index):
if index < 0 or index >= self.get_length():
raise Exception("Invalid index")
if index == 0:
self.head = self.head.next
return
current = self.head
current_index = 0
while current:
if current_index == index - 1:
current.next = current.next.next
break
current = current.next
current_index += 1
def get_length(self):
current = self.head
length = 0
while current:
length += 1
current = current.next
return length
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
```
这里实现了插入节点的三种方式:
- insert_at_beginning:在链表头部插入节点
- insert_at_end:在链表尾部插入节点
- insert_at_index:在指定位置插入节点
同时还实现了删除节点和遍历节点的方法。
下面是一个使用示例:
```python
linked_list = LinkedList()
linked_list.insert_at_beginning(2)
linked_list.insert_at_beginning(1)
linked_list.insert_at_end(4)
linked_list.insert_at_index(2, 3)
linked_list.display() # 1 -> 2 -> 3 -> 4 -> None
linked_list.delete_at_index(1)
linked_list.display() # 1 -> 3 -> 4 -> None
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)