python wed自动化面试题
时间: 2023-10-21 21:09:48 浏览: 34
链表基本操作的函数实现如下:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(nullptr) {}
};
class LinkedList {
public:
LinkedList() {
head = new ListNode(0);
}
void insert(int val) {
ListNode* node = new ListNode(val);
node->next = head->next;
head->next = node;
}
void remove(int val) {
ListNode* pre = head;
while (pre->next && pre->next->val != val) {
pre = pre->next;
}
if (pre->next) {
ListNode* delNode = pre->next;
pre->next = delNode->next;
delete delNode;
}
}
bool find(int val) {
ListNode* cur = head->next;
while (cur && cur->val != val) {
cur = cur->next;
}
if (cur) {
return true;
}
else {
return false;
}
}
void print() {
ListNode* cur = head->next;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
ListNode* predecessor(int val) {
ListNode* pre = head;
while (pre->next && pre->next->val != val) {
pre = pre->next;
}
return pre;
}
ListNode* successor(int val) {
ListNode* cur = head->next;
while (cur && cur->val != val) {
cur = cur->next;
}
if (cur && cur->next) {
return cur->next;
}
else {
return nullptr;
}
}
void merge(LinkedList& other) {
ListNode* cur1 = head->next;
ListNode* cur2 = other.head->next;
ListNode* pre = head;
while (cur1 && cur2) {
if (cur1->val < cur2->val) {
pre = cur1;
cur1 = cur1->next;
}
else {
ListNode* node = cur2;
cur2 = cur2->next;
node->next = pre->next;
pre->next = node;
pre = pre->next;
}
}
if (cur2) {
pre->next = cur2;
other.head->next = nullptr;
}
}
void clear() {
ListNode* cur = head->next;
while (cur) {
ListNode* delNode = cur;
cur = cur->next;
delete delNode;
}
head->next = nullptr;
}
void destroy() {
clear();
delete head;
head = nullptr;
}
int length() {
int len = 0;
ListNode* cur = head->next;
while (cur) {
len++;
cur = cur->next;
}
return len;
}
int get(int pos) {
ListNode* cur = head->next;
while (cur && pos > 0) {
cur = cur->next;
pos--;
}
if (cur) {
return cur->val;
}
else {
return -1;
}
}
private:
ListNode* head;
};
```
其中,`ListNode` 表示链表的结点结构体,`LinkedList` 类实现了链表的基本操作,包括:
- `insert`:在链表头插入一个元素;
- `remove`:删除链表中第一个值等于给定值的结点;
- `find`:查找链表中是否存在给定值的结点;
- `print`:输出整个链表;
- `predecessor`:查找给定值的前驱结点;
- `successor`:查找给定值的后继结点;
- `merge`:合并两个有序链表;
- `clear`:将链表置为空表;
- `destroy`:销毁链表;
- `length`:求链表的长度;
- `get`:获取某位置结点的内容。
下面是一个示例程序:
```c++
int main() {
LinkedList list;
list.insert(1);
list.insert(3);
list.insert(5);
list.insert(7);
list.print(); // 7 5 3 1
list.remove(3);
list.print(); // 7 5 1
cout << list.find(5) << endl; // 1
cout << list.find(3) << endl; // 0
cout << list.length() << endl; // 3
cout << list.get(1) << endl; // 5
LinkedList other;
other.insert(2);
other.insert(4);
other.insert(6);
other.print(); // 6 4 2
list.merge(other);
list.print(); // 7 6 5 4 2 1
list.destroy();
return 0;
}
```