通过数据结构的知识编写一个程序。建立单链表,在单链表中实现插入,删除和查找操作。将两个递增的有序单链表合并成一个非递减的有序单链表
时间: 2024-09-30 11:12:46 浏览: 38
创建一个单链表并实现插入、删除和查找操作,以及合并两个递增有序单链表,我们可以按照以下步骤来进行:
首先,我们需要定义链表节点的基本结构,包含一个值和指向下一个节点的指针:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
接下来,我们定义链表类,包含插入、删除和查找函数:
```python
class LinkedList:
def __init__(self):
self.head = None
# 插入节点
def insert(self, val):
if not self.head:
self.head = ListNode(val)
else:
new_node = ListNode(val)
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除节点(这里以删除值为例)
def delete(self, val):
if self.head is None or self.head.val == val:
self.head = self.head.next
return
current = self.head
prev = None
while current and current.val != val:
prev = current
current = current.next
if current:
prev.next = current.next
# 查找节点
def search(self, val):
current = self.head
while current:
if current.val == val:
return True
current = current.next
return False
```
最后,合并两个递增有序的链表:
```python
def merge_sorted_lists(list1, list2):
dummy = ListNode(0) # 创建虚拟头节点
tail = dummy
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
if list1:
tail.next = list1
elif list2:
tail.next = list2
return dummy.next
```
现在你可以用这个`LinkedList`类来创建链表,进行各种操作,并合并两个递增有序链表了。
阅读全文