在C语言中,数据结构可以通过定义结构体来实现
在C语言中,数据结构可以通过定义结构体来实现。以下是一些常见的数据结构的使用方法示例:
- 链表:
#include<stdio.h>
#include<stdlib.h>
structNode{
intdata;
structNode*next;
};
intmain(){
structNode*head=NULL;
//创建节点并添加到链表
structNode*node1=(structNode*)malloc(sizeof(structNode));
node1->data=1;
node1->next=NULL;
head=node1;
structNode*node2=(structNode*)malloc(sizeof(structNode));
node2->data=2;
node2->next=NULL;
node1->next=node2;
//遍历链表并打印节点的数据
structNode*current=head;
while(current!=NULL){
printf("%d\n",current->data);
current=current->next;
}
return0;
}
#include<stdio.h>
#defineMAX_SIZE100
structStack{
intdata[MAX_SIZE];
inttop;
};
voidpush(structStack*stack,intvalue){
if(stack->top==MAX_SIZE-1){
printf("Stackisfull.\n");
return;
}
stack->data[++stack->top]=value;
}
intpop(structStack*stack){
if(stack->top==-1){
printf("Stackisempty.\n");
return-1;
}
returnstack->data[stack->top--];
}
intmain(){
structStackstack;
stack.top=-1;
push(&stack,1);
push(&stack,2);
printf("%d\n",pop(&stack));
printf("%d\n",pop(&stack));
return0;
}
#include<stdio.h>
#defineMAX_SIZE100
structQueue{
intdata[MAX_SIZE];
intfront,rear;
};
voidenqueue(structQueue*queue,intvalue){
if(queue->rear==MAX_SIZE-1){
printf("Queueisfull.\n");
return;
}
queue->data[++queue->rear]=value;
}
intdequeue(structQueue*queue){
if(queue->front>queue->rear){
printf("Queueisempty.\n");
return-1;
}
returnqueue->data[queue->front++];
}
intmain(){
structQueuequeue;
queue.front=0;
queue.rear=-1;
enqueue(&queue,1);
enqueue(&queue,2);
printf("%d\n",dequeue(&queue));
printf("%d\n",dequeue(&queue));
return0;
}
以上是一些常见数据结构的使用方法示例,当然还有其他更复杂的数据结构和操作方式,可以根据具体需求选择合适的数据结构。
版权声明
本文仅代表作者观点,不代表博信信息网立场。