栈:头添加头删除
#include<stdio.h>
#include<stdlib.h>
typedef struct node1
{
int nValue;
struct node1 *pNext;
}MyStack;
typedef struct node2
{
int nCount;
MyStack *pTop;
}Stack;
void s_Init(Stack **pStack)
{
*pStack = (Stack*)malloc(sizeof(Stack));
(*pStack)->nCount = 0;
(*pStack)->pTop = NULL;
}
void s_Push(Stack *pStack,int nNum)
{
if(pStack == NULL)return;
MyStack *pTemp = NULL;
pTemp = (MyStack*)malloc(sizeof(MyStack));
pTemp->nValue = nNum;
pTemp->pNext = pStack->pTop;
pStack->pTop = pTemp;
pStack->nCount++;
}
int s_Pop(Stack *pStack)
{
if(pStack == NULL || pStack->nCount == 0)return -1;
MyStack *pDel = NULL;
int nNum;
pDel = pStack->pTop;
nNum = pDel->nValue;
pStack->pTop = pStack->pTop->pNext;
free(pDel);
pDel = NULL;
pStack->nCount--;
return nNum;
}
void s_Clear(Stack *pStack)
{
if(pStack == NULL || pStack->nCount == 0)return;
while(pStack->nCount != 0)
{
s_Pop(pStack);
}
}
void s_Destroy(Stack **pStack)
{
s_Clear(*pStack);
free(*pStack);
*pStack = NULL;
}
MyStack *s_GetTop(Stack *pStack)
{
if(pStack == NULL)exit(1);
return pStack->pTop;
}
int s_GetCount(Stack *pStack)
{
if(pStack == NULL)return -1;
return pStack->nCount;
}
int s_IsEmpty(Stack *pStack)
{
if(pStack == NULL)exit(1);
return pStack->nCount == 0 ? 1 :0;
}
int main()
{
Stack *pStack = NULL;
s_Init(&pStack);
s_Push(pStack,1);
s_Push(pStack,2);
s_Push(pStack,3);
s_Push(pStack,4);
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
s_Destroy(&pStack);
s_Push(pStack,1000);
printf("%d\n",s_Pop(pStack));
return 0;
}
队列:尾添加头删除
#include<stdio.h>
#include<stdlib.h>
typedef struct node3
{
int nValue;
struct node3 *pNext;
}MyQueue;
typedef struct node4
{
int nCount;
MyQueue *pHead;
MyQueue *pTail;
}Queue;
void q_Init(Queue **pQueue)
{
*pQueue = (Queue*)malloc(sizeof(Queue));
(*pQueue)->nCount = 0;
(*pQueue)->pHead = NULL;
(*pQueue)->pTail = NULL;
}
void q_Push(Queue *pQueue,int nNum)
{
if(pQueue == NULL)return;
MyQueue *pTemp = NULL;
pTemp = (MyQueue*)malloc(sizeof(MyQueue));
pTemp->nValue = nNum;
pTemp->pNext = NULL;
//尾添加
if(pQueue->pHead == NULL)
{
pQueue->pHead = pTemp;
}
else
{
pQueue->pTail->pNext = pTemp;
}
pQueue->pTail = pTemp;
pQueue->nCount++;
}
int q_Pop(Queue *pQueue)
{
if(pQueue == NULL || pQueue->nCount == 0)return -1;
MyQueue *pDel = NULL;
pDel = pQueue->pHead;
int nNum;
nNum = pDel->nValue;
pQueue->pHead = pQueue->pHead->pNext;
free(pDel);
pDel = NULL;
pQueue->nCount--;
if(pQueue->nCount == 0)
{
pQueue->pTail = NULL;
}
return nNum;
}
int q_IsEmpty(Queue *pQueue)
{
if(pQueue == NULL)exit(1);
return pQueue->nCount == 0?1:0;
}
int main()
{
Queue *pQueue = NULL;
q_Init(&pQueue);
q_Push(pQueue,1);
q_Push(pQueue,2);
q_Push(pQueue,3);
q_Push(pQueue,4);
printf("%d\n",q_Pop(pQueue));
printf("%d\n",q_Pop(pQueue));
printf("%d\n",q_Pop(pQueue));
printf("%d\n",q_Pop(pQueue));
return 0;
}