C语言数据结构简单算法演示系统
时间: 2023-07-25 19:24:05 浏览: 50
好的,以下是一个简单的C语言数据结构算法演示系统的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 创建链表
struct Node* createList() {
int n, i;
struct Node *head, *p, *tail;
head = (struct Node*)malloc(sizeof(struct Node)); // 创建头节点
tail = head; // 尾指针初始化为头节点
printf("请输入链表长度:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
p = (struct Node*)malloc(sizeof(struct Node)); // 创建新节点
printf("请输入节点值:");
scanf("%d", &p->data);
tail->next = p; // 尾节点指向新节点
tail = p; // 尾指针指向新节点
}
tail->next = NULL; // 尾节点指向空
return head; // 返回头节点
}
// 遍历链表
void traverseList(struct Node* head) {
struct Node* p = head->next; // 指向第一个节点
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 插入节点
void insertNode(struct Node* head, int index, int value) {
int i;
struct Node *p, *q;
p = head;
for (i = 0; i < index - 1; i++) {
p = p->next; // 移动到插入位置的前一个节点
}
q = (struct Node*)malloc(sizeof(struct Node)); // 创建新节点
q->data = value;
q->next = p->next;
p->next = q;
}
// 删除节点
void deleteNode(struct Node* head, int index) {
int i;
struct Node *p, *q;
p = head;
for (i = 0; i < index - 1; i++) {
p = p->next; // 移动到删除位置的前一个节点
}
q = p->next;
p->next = q->next;
free(q); // 释放删除节点的空间
}
int main() {
struct Node* head;
head = createList();
printf("链表内容:");
traverseList(head);
insertNode(head, 3, 5);
printf("插入节点后:");
traverseList(head);
deleteNode(head, 2);
printf("删除节点后:");
traverseList(head);
return 0;
}
```
这个演示系统展示了一个简单的链表操作,包括创建链表、遍历链表、插入节点和删除节点。您可以根据自己的需要,扩展和改进这个演示系统,展示更多的数据结构和算法操作。
希望这个代码示例对您有所帮助。