admin 管理员组文章数量: 1086019
2024年5月20日发(作者:mythical)
数据结构c语言程序
下面是一个使用C语言实现的简单数据结构示例:链表。
```c
#include
#include
// 链表节点结构
struct Node {
int data; // 节点数据
struct Node* next; // 下一个节点指针
};
// 创建一个新的节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表的末尾插入一个节点
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 在链表的开头插入一个节点
void insertAtBegin(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
newNode->next = *head;
*head = newNode;
}
}
// 删除链表中第一个值为data的节点
void deleteNode(struct Node** head, int data) {
if (*head == NULL) {
return;
}
struct Node* temp = *head;
if (temp->data == data) {
*head = temp->next;
} else {
struct Node* prev = NULL;
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
}
free(temp);
}
// 打印链表的所有节点
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("n");
}
int main() {
struct Node* head = NULL;
// 在链表末尾插入节点
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
printf("链表: ");
printList(head);
// 在链表开头插入节点
insertAtBegin(&head, 0);
printf("链表: ");
printList(head);
// 删除节点
deleteNode(&head, 2);
printf("链表: ");
printList(head);
return 0;
}
```
这个程序实现了链表的基本操作,包括在链表末尾插入节点、
在链表开头插入节点和删除链表中特定值的节点。程序的主要
部分是在`main`函数中对链表进行测试。运行这个程序会输出
链表的状态:
```
链表: 1 2 3
链表: 0 1 2 3
链表: 0 1 3
```
这个程序演示了一个简单的数据结构实现,你可以根据自己的
需求进行修改和扩展。
版权声明:本文标题:数据结构c语言程序 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/b/1716213210a692164.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论