预处理
# include <stdio.h>
# include <malloc.h>
# include <assert.h>
封装节点
typedef struct Node {
int data;
struct Node * next;
} * LPNODE;
封装链式结构
typedef struct List {
LPNODE frontNode;
LPNODE tailNode;
int CurSize;
} * LPLIST;
创建节点
LPNODE CreateNode ( int data) {
LPNODE newNode = ( LPNODE) malloc ( sizeof ( Node) ) ;
assert ( newNode) ;
newNode-> data = data;
newNode-> next = NULL ;
return newNode;
}
创建链表
LPLIST CreateList ( ) {
LPLIST list = ( LPLIST) malloc ( sizeof ( List) ) ;
assert ( list) ;
list-> CurSize = 0 ;
list-> frontNode = NULL ;
list-> tailNode = NULL ;
return list;
}
入队
void Push ( LPLIST list, int data) {
LPNODE newNode = CreateNode ( data) ;
if ( list-> CurSize == 0 )
list-> frontNode = newNode;
else
list-> tailNode-> next = newNode;
list-> tailNode = newNode;
list-> CurSize++ ;
}
出队
void Pop ( LPLIST list) {
LPNODE tempNode = list-> frontNode-> next;
free ( list-> frontNode) ;
list-> frontNode = tempNode;
list-> CurSize-- ;
}
获取队列元素
int Front ( LPLIST list) {
return list-> frontNode-> data;
}
判空
bool temp ( LPLIST list) {
return list-> CurSize == 0 ;
}
测试代码
int main ( ) {
LPLIST list = CreateList ( ) ;
printf ( "\n入队:\t" ) ;
for ( int i = 0 ; i < 5 ; i++ ) {
printf ( "%d\t" , i) ;
Push ( list, i) ;
}
printf ( "\n出队:\t" ) ;
while ( ! temp ( list) ) {
printf ( "%d\t" , Front ( list) ) ;
Pop ( list) ;
}
return 0 ;
}
运行效果