单链表的基本操作,参考附件的代码,完成单链表的创建(尾插法和头插法)、输出链表、查找链表的第k个结点、在链表的第k个结点后插入新结点、在链表的第k个结点前插入新结点、删除链表的第k个结点等函数。
时间: 2024-11-20 09:35:18 浏览: 12
单链表是一种线性数据结构,每个节点包含两个部分:数据域和指针域,其中指针域指向下一个节点。以下是单链表的一些基本操作:
1. **链表创建** (尾插法):
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def append(head, data):
if not head:
head = Node(data)
else:
current = head
while current.next:
current = current.next
current.next = Node(data)
return head
```
(头插法) 可以类似地实现,但在头部插入节点:
```python
def prepend(head, data):
new_node = Node(data)
new_node.next = head
return new_node
```
2. **输出链表**:
```python
def print_list(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
```
3. **查找第k个节点**:
```python
def find_kth_node(head, k):
count = 0
current = head
while current and count < k:
count += 1
current = current.next
if count == k:
return current
else:
return None
```
4. **在第k个节点后插入新节点**:
```python
def insert_after_kth(head, k, data):
if not head or k <= 0:
return None
node_to_insert = find_kth_node(head, k)
if not node_to_insert:
return None
new_node = Node(data)
new_node.next = node_to_insert.next
node_to_insert.next = new_node
return head
```
5. **在第k个节点前插入新节点**:
```python
def insert_before_kth(head, k, data):
if not head or k <= 0:
return None
if k == 1:
return prepend(head, data)
previous_node = find_kth_node(head, k - 1)
if previous_node:
new_node = Node(data)
new_node.next = previous_node.next
previous_node.next = new_node
return head
```
6. **删除第k个节点**:
```python
def delete_kth_node(head, k):
if not head or k <= 0:
return head
if k == 1:
return head.next
current = head
for _ in range(k - 1):
current = current.next
if current is None or current.next is None:
return head
current.next = current.next.next
return head
```
阅读全文