在Visual Studio2010中使用C语言实现:带表头结点单链表的建立,清空,插入,删除,查找,修改,以及单链表的逆置和排序运算。
时间: 2023-04-12 15:02:04 浏览: 150
好的,以下是带表头结点单链表的建立、清空、插入、删除、查找、修改、逆置和排序运算的C语言实现代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
// 创建链表
LinkedList createList() {
LinkedList head = (LinkedList)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 清空链表
void clearList(LinkedList head) {
Node *p = head->next;
while (p != NULL) {
Node *temp = p->next;
free(p);
p = temp;
}
head->next = NULL;
}
// 插入节点
void insertNode(LinkedList head, int data, int index) {
Node *p = head;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p == NULL || i > index) {
printf("插入位置不合法\n");
return;
}
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
}
// 删除节点
void deleteNode(LinkedList head, int index) {
Node *p = head;
int i = 0;
while (p->next != NULL && i < index) {
p = p->next;
i++;
}
if (p->next == NULL || i > index) {
printf("删除位置不合法\n");
return;
}
Node *temp = p->next;
p->next = temp->next;
free(temp);
}
// 查找节点
int findNode(LinkedList head, int data) {
Node *p = head->next;
int i = 0;
while (p != NULL) {
if (p->data == data) {
return i;
}
p = p->next;
i++;
}
return -1;
}
// 修改节点
void modifyNode(LinkedList head, int data, int index) {
Node *p = head->next;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p == NULL || i > index) {
printf("修改位置不合法\n");
return;
}
p->data = data;
}
// 链表逆置
void reverseList(LinkedList head) {
Node *p = head->next;
Node *pre = NULL;
while (p != NULL) {
Node *temp = p->next;
p->next = pre;
pre = p;
p = temp;
}
head->next = pre;
}
// 链表排序
void sortList(LinkedList head) {
Node *p = head->next;
int len = 0;
while (p != NULL) {
len++;
p = p->next;
}
for (int i = 0; i < len - 1; i++) {
p = head->next;
for (int j = 0; j < len - i - 1; j++) {
if (p->data > p->next->data) {
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
}
// 打印链表
void printList(LinkedList head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkedList list = createList();
insertNode(list, 1, 0);
insertNode(list, 2, 1);
insertNode(list, 3, 2);
insertNode(list, 4, 3);
printf("原始链表:");
printList(list);
deleteNode(list, 2);
printf("删除节点后的链表:");
printList(list);
modifyNode(list, 5, 1);
printf("修改节点后的链表:");
printList(list);
reverseList(list);
printf("逆置后的链表:");
printList(list);
sortList(list);
printf("排序后的链表:");
printList(list);
clearList(list);
printf("清空后的链表:");
printList(list);
return 0;
}
```
希望这个代码能够帮到你。
阅读全文