底部称为栈底,顶部称为栈顶,所有的操作只能在栈顶进行
栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构
struct listnode{
int data;
struct listnode *next;
};
typedef struct listnode* node;
void initstack(node head) {
head->next = NULL;
}
//入栈
bool pushstack(node head, int ele){
node stack = malloc(sizeof(struct listnode));
if(stack==NULL)
return 0;
stack->data = ele;
stack->next = head->next;
head->next = stack;
return 1;
}
//出栈
int popstack(node head){
int pop_data;
node pop_stack = head->next;
pop_data = pop_stack->data;
head->next = head->next->next;
free(pop_stack);
return pop_data;
}
//打印
void printStack(node head){
head = head->next;
while(head != NULL){
printf("&d", head->data);
head = head->next;
}
}
队列
队列中的元素只能从队尾进入,只能从队首出去.
对于初始化需要初始化两个类型,一个是初始化结点,一个是初始化队列。代码中的描述,初始化队列有些不同,当初始化队列的时候,需要将头尾两个结点指向的内容统统置为空。
当Q->front == NULL 并且 Q->rear == NULL 时,链队列为空。
//节点初始化
struct queuenode{
int data;
struct queuenode *next;
};
typedef struct queuenode* queuenode_t;
//头尾
struct queue{
queuenode_t rear;
queuenode_t front;
};
//队列初始化
typedef struct queue* queue_t;
bool queue_init(queue_t Q)
{
queuenode_t node = malloc(sizeof(struct queuenode));
if(node == NULL)
return 0;
Q->rear = Q->front = node;
}
//入列
bool inqueue(queue_t Q, int data)
{
queuenode_t node = malloc(sizeof(struct queuenode));
node->data = data;
node->next = Q->rear->next;
Q->rear->next = node;
}
//出列
int outqueue(queue_t Q){
int ele;
queuenode_t node = Q->front->next;
ele = node->data = Q->front->next->data;
Q->front->next = Q->front->next->next;
if (Q->rear == node)
Q->rear = Q->front;
free(node);
return ele;
}
//打印
void printqueue(queue_t Q){
queuenode_t node = Q->front->next;
do
{
printf("%d", node->data);
node = node->next;
} while (node == Q->rear);
}