数据结构 C++ 代码
时间: 2023-10-19 11:29:41 浏览: 35
当然,我可以为您提供一些常见的数据结构的C代码示例。以下是几个常见的数据结构及其对应的C代码示例:
1. 数组(Array):
```
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
// 访问数组元素
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
2. 链表(Linked List):
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点
struct Node {
int data;
struct Node* next;
};
// 打印链表
void printLinkedList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
// 创建链表结点
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 打印链表
printLinkedList(head);
return 0;
}
```
3. 栈(Stack):
```
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
// 入栈
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = item;
}
}
// 出栈
int pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
// 打印栈顶元素
int peek() {
if (top < 0) {
printf("Stack is empty\n");
return -1;
} else {
return stack[top];
}
}
// 判断栈是否为空
int isEmpty() {
return top < 0;
}
int main() {
push(1);
push(2);
push(3);
printf("Top element: %d\n", peek());
printf("Elements: ");
while (!isEmpty()) {
printf("%d ", pop());
}
printf("\n");
return 0;
}
```
这些是常见的数据结构的C代码示例。希望对您有所帮助!如果你需要其他数据结构或更多代码示例,请告诉我。