请用c++编程实现一个对单链表表进行基本操作的系统,主要包括表的创建,输入,查询,取值,插入,删除和输出等操作(可以采用带头结点和不带头结点的单链表)
时间: 2024-05-29 12:10:42 浏览: 68
c++实现单链表基本操作
5星 · 资源好评率100%
以下是使用带头结点的单链表实现的代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 定义链表结构体
typedef struct LinkedList {
Node *head;
int length;
} LinkedList;
// 创建链表
LinkedList *createLinkedList() {
LinkedList *list = (LinkedList *)malloc(sizeof(LinkedList));
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
list->head = head;
list->length = 0;
return list;
}
// 在链表末尾插入元素
void appendLinkedList(LinkedList *list, int data) {
Node *p = list->head;
while (p->next != NULL) {
p = p->next;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
p->next = newNode;
list->length++;
}
// 在链表指定位置插入元素
void insertLinkedList(LinkedList *list, int data, int index) {
if (index < 0 || index > list->length) {
printf("Invalid index!\n");
return;
}
Node *p = list->head;
int i = 0;
while (i < index) {
p = p->next;
i++;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
list->length++;
}
// 删除链表指定位置的元素
void deleteLinkedList(LinkedList *list, int index) {
if (index < 0 || index >= list->length) {
printf("Invalid index!\n");
return;
}
Node *p = list->head;
int i = 0;
while (i < index) {
p = p->next;
i++;
}
Node *temp = p->next;
p->next = temp->next;
free(temp);
list->length--;
}
// 获取链表指定位置的元素
int getLinkedList(LinkedList *list, int index) {
if (index < 0 || index >= list->length) {
printf("Invalid index!\n");
return -1;
}
Node *p = list->head->next;
int i = 0;
while (i < index) {
p = p->next;
i++;
}
return p->data;
}
// 在链表中查找指定元素
int searchLinkedList(LinkedList *list, int data) {
Node *p = list->head->next;
int index = 0;
while (p != NULL) {
if (p->data == data) {
return index;
}
p = p->next;
index++;
}
return -1;
}
// 输出链表
void printLinkedList(LinkedList *list) {
Node *p = list->head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkedList *list = createLinkedList();
appendLinkedList(list, 1);
appendLinkedList(list, 2);
appendLinkedList(list, 3);
printLinkedList(list); // 1 2 3
insertLinkedList(list, 4, 1);
printLinkedList(list); // 1 4 2 3
deleteLinkedList(list, 2);
printLinkedList(list); // 1 4 3
int data = getLinkedList(list, 1);
printf("%d\n", data); // 4
int index = searchLinkedList(list, 3);
printf("%d\n", index); // 2
return 0;
}
阅读全文