数据结构实验之查出的相关操作的代码
时间: 2024-03-09 10:48:19 浏览: 67
以下是常见数据结构操作的代码示例:
## 数组操作
### 初始化数组
```python
arr = [0] * n
```
### 遍历数组
```python
for i in range(n):
print(arr[i])
```
### 查找元素
```python
if x in arr:
print("元素 x 存在")
else:
print("元素 x 不存在")
```
### 插入元素
```python
arr.append(x)
```
### 删除元素
```python
arr.remove(x)
```
### 数组排序
```python
arr.sort()
```
## 链表操作
### 定义链表节点类
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
### 遍历链表
```python
cur = head
while cur:
print(cur.val)
cur = cur.next
```
### 查找元素
```python
cur = head
while cur:
if cur.val == x:
print("元素 x 存在")
break
cur = cur.next
else:
print("元素 x 不存在")
```
### 插入元素
```python
new_node = ListNode(x)
new_node.next = head
head = new_node
```
### 删除元素
```python
if head.val == x:
head = head.next
else:
cur = head
while cur.next:
if cur.next.val == x:
cur.next = cur.next.next
break
cur = cur.next
```
## 栈操作
### 定义栈类
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
```
### 入栈
```python
stack.push(x)
```
### 出栈
```python
stack.pop()
```
### 查看栈顶元素
```python
stack.peek()
```
### 判断栈是否为空
```python
stack.is_empty()
```
## 队列操作
### 定义队列类
```python
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
def size(self):
return len(self.items)
```
### 入队
```python
queue.enqueue(x)
```
### 出队
```python
queue.dequeue()
```
### 判断队列是否为空
```python
queue.is_empty()
```
阅读全文