数据结构c语言版源代码
时间: 2023-06-01 07:01:45 浏览: 73
这个问题比较广泛,数据结构包含很多内容,可能需要很多不同的源代码。以下是一些常见的数据结构及其C语言版源代码示例:
1. 数组:
```
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
2. 链表:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
}
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;
printList(head);
return 0;
}
```
3. 栈:
```
#include <stdio.h>
#define MAX_SIZE 100
struct Stack {
int top;
int arr[MAX_SIZE];
};
void push(struct Stack* s, int item) {
if (s->top == MAX_SIZE - 1) {
printf("Stack Overflow!");
return;
}
s->top++;
s->arr[s->top] = item;
}
int pop(struct Stack* s) {
if (s->top == -1) {
printf("Stack Underflow!");
return -1;
}
int item = s->arr[s->top];
s->top--;
return item;
}
int main() {
struct Stack s;
s.top = -1;
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("%d ", pop(&s));
printf("%d ", pop(&s));
printf("%d ", pop(&s));
printf("%d ", pop(&s));
return 0;
}
```
4. 队列:
```
#include <stdio.h>
#define MAX_SIZE 100
struct Queue {
int front, rear;
int arr[MAX_SIZE];
};
void enqueue(struct Queue* q, int item) {
if (q->rear == MAX_SIZE - 1) {
printf("Queue Overflow!");
return;
}
q->arr[++q->rear] = item;
}
int dequeue(struct Queue* q) {
if (q->front > q->rear) {
printf("Queue Underflow!");
return -1;
}
return q->arr[q->front++];
}
int main() {
struct Queue q;
q.front = 0;
q.rear = -1;
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("%d ", dequeue(&q));
printf("%d ", dequeue(&q));
printf("%d ", dequeue(&q));
printf("%d ", dequeue(&q));
return 0;
}
```
5. 树:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int item) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
inorder(root);
return 0;
}
```
这些示例只是数据结构的冰山一角,如果您需要更多不同类型的数据结构,请参考其他资源或书籍。