设计一组整数,完成链表(带表头结点)的基本操作。建立链表、插入、删除、查找、输出、求前驱、求后继、两个有序链表的合并操作。 其他基本操作还有销毁链表、将链表置为空表、求链表的长度、获取某位置结点的内容、搜索结点、销毁等。
时间: 2023-10-06 13:12:35 浏览: 72
链表基本操作的实现:
1. 建立链表
```c++
typedef struct node {
int data;
struct node *next;
}Node;
Node *createList() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
return head;
}
```
2. 插入
```c++
void insert(Node *head, int data) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = data;
p->next = head->next;
head->next = p;
}
```
3. 删除
```c++
void remove(Node *head, int data) {
Node *p = head->next;
Node *pre = head;
while (p != NULL) {
if (p->data == data) {
pre->next = p->next;
free(p);
break;
}
pre = p;
p = p->next;
}
}
```
4. 查找
```c++
Node *find(Node *head, int data) {
Node *p = head->next;
while (p != NULL) {
if (p->data == data) {
return p;
}
p = p->next;
}
return NULL;
}
```
5. 输出
```c++
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
6. 求前驱
```c++
Node *getPre(Node *head, int data) {
Node *p = head->next;
Node *pre = head;
while (p != NULL) {
if (p->data == data) {
return pre;
}
pre = p;
p = p->next;
}
return NULL;
}
```
7. 求后继
```c++
Node *getNext(Node *head, int data) {
Node *p = head->next;
while (p != NULL && p->data != data) {
p = p->next;
}
if (p != NULL) {
return p->next;
}
return NULL;
}
```
8. 合并有序链表
```c++
Node *mergeList(Node *head1, Node *head2) {
Node *p1 = head1->next;
Node *p2 = head2->next;
Node *head = createList();
Node *p = head;
while (p1 != NULL && p2 != NULL) {
if (p1->data < p2->data) {
p->next = p1;
p1 = p1->next;
} else {
p->next = p2;
p2 = p2->next;
}
p = p->next;
}
if (p1 != NULL) {
p->next = p1;
}
if (p2 != NULL) {
p->next = p2;
}
return head;
}
```
9. 销毁链表
```c++
void destroyList(Node *head) {
Node *p = head->next;
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
head->next = NULL;
}
```
10. 将链表置为空表
```c++
void clearList(Node *head) {
destroyList(head);
}
```
11. 求链表的长度
```c++
int length(Node *head) {
int len = 0;
Node *p = head->next;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
```
12. 获取某位置结点的内容
```c++
int get(Node *head, int index) {
Node *p = head->next;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p != NULL) {
return p->data;
}
return -1;
}
```
13. 搜索结点
```c++
bool search(Node *head, int data) {
Node *p = head->next;
while (p != NULL) {
if (p->data == data) {
return true;
}
p = p->next;
}
return false;
}
```
14. 销毁
```c++
void destroy(Node *head) {
free(head);
}
```