编写完整程序,建立一个整数数字链表,练习在链表中插入、删除、查找某个数值x,并求链表长度)
时间: 2023-08-15 21:41:25 浏览: 57
好的,以下是一个完整的程序:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add_at_head(self, val):
new_head = ListNode(val)
new_head.next = self.head
self.head = new_head
def add_at_tail(self, val):
if not self.head:
self.head = ListNode(val)
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = ListNode(val)
def delete_node(self, val):
if not self.head:
return
if self.head.val == val:
self.head = self.head.next
return
prev = self.head
curr = self.head.next
while curr and curr.val != val:
prev = curr
curr = curr.next
if curr:
prev.next = curr.next
def find_node(self, val):
curr = self.head
while curr and curr.val != val:
curr = curr.next
if curr:
return True
return False
def get_length(self):
curr = self.head
length = 0
while curr:
length += 1
curr = curr.next
return length
```
这个程序定义了两个类:`ListNode` 和 `LinkedList`。`ListNode` 表示链表中的一个节点,它有一个值 `val` 和一个指向下一个节点的指针 `next`。`LinkedList` 表示整个链表,它有一个头节点 `head`。
`LinkedList` 类有以下几个方法:
- `add_at_head(val)`:在链表头部插入一个新节点,值为 `val`。
- `add_at_tail(val)`:在链表尾部插入一个新节点,值为 `val`。
- `delete_node(val)`:删除链表中第一个值为 `val` 的节点。
- `find_node(val)`:查找链表中是否存在值为 `val` 的节点,如果存在返回 `True`,否则返回 `False`。
- `get_length()`:返回链表的长度。
你可以通过以下代码测试这个程序:
```python
# 创建链表
ll = LinkedList()
ll.add_at_head(3)
ll.add_at_head(2)
ll.add_at_head(1)
ll.add_at_tail(4)
ll.add_at_tail(5)
# 输出链表长度
print(ll.get_length())
# 查找节点
print(ll.find_node(3))
print(ll.find_node(6))
# 删除节点
ll.delete_node(3)
print(ll.get_length())
print(ll.find_node(3))
```
相关推荐
![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)