用c++代码写一个链表,实现常见的链表操作,插入头部,尾部,某数据之后或之前,修改,删除,排序,存储到文件,从文件构建链表,判空,是否存在,清空,排序
时间: 2024-05-01 08:16:40 浏览: 90
《数据结构与算法》课程上机实验二(链表)_链表_fruitd55_C++_数据结构与算法_
```
#include<stdio.h>
#include<stdlib.h>
//定义链表节点
typedef struct node {
int data;
struct node *next;
}Node, *LinkedList;
//初始化链表
LinkedList InitList() {
LinkedList L = (LinkedList)malloc(sizeof(Node));
L->next = NULL;
return L;
}
//插入节点到链表头部
LinkedList InsertHead(LinkedList L, int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
return L;
}
//插入节点到链表尾部
LinkedList InsertTail(LinkedList L, int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
Node *p = L;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
return L;
}
//插入节点到某数据之后
LinkedList InsertAfter(LinkedList L, int data, int after) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
Node *p = L->next;
while (p != NULL && p->data != after) {
p = p->next;
}
if (p == NULL) {
printf("Insert failed! Cannot find %d in linked list!\n", after);
return L;
}
node->next = p->next;
p->next = node;
return L;
}
//插入节点到某数据之前
LinkedList InsertBefore(LinkedList L, int data, int before) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
Node *pre = L;
Node *p = L->next;
while (p != NULL && p->data != before) {
pre = p;
p = p->next;
}
if (p == NULL) {
printf("Insert failed! Cannot find %d in linked list!\n", before);
return L;
}
node->next = p;
pre->next = node;
return L;
}
//修改某个节点的值
LinkedList Modify(LinkedList L, int data, int newData) {
Node *p = L->next;
while (p != NULL && p->data != data) {
p = p->next;
}
if (p == NULL) {
printf("Modify failed! Cannot find %d in linked list!\n", data);
return L;
}
p->data = newData;
return L;
}
//删除某个节点
LinkedList Delete(LinkedList L, int data) {
Node *pre = L;
Node *p = L->next;
while (p != NULL && p->data != data) {
pre = p;
p = p->next;
}
if (p == NULL) {
printf("Delete failed! Cannot find %d in linked list!\n", data);
return L;
}
pre->next = p->next;
free(p);
return L;
}
//判断链表是否为空
int IsEmpty(LinkedList L) {
return L->next == NULL;
}
//判断某个数据是否在链表中
int IsExist(LinkedList L, int data) {
Node *p = L->next;
while (p != NULL && p->data != data) {
p = p->next;
}
return p != NULL;
}
//清空链表
LinkedList Clear(LinkedList L) {
Node *p = L->next;
while (p != NULL) {
Node *next = p->next;
free(p);
p = next;
}
L->next = NULL;
return L;
}
//排序链表
LinkedList Sort(LinkedList L) {
Node *p = L->next;
int temp;
while (p != NULL) {
Node *q = p->next;
while (q != NULL) {
if (p->data > q->data) {
temp = p->data;
p->data = q->data;
q->data = temp;
}
q = q->next;
}
p = p->next;
}
return L
阅读全文