栈
栈的概念和结构
栈是一种特殊的线性表,只允许在固定的一端进行元素的插入和删除元素的操作。进行数据的插入和删除的操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵顼后进先出(Last In First Out)的规则。
压栈:栈的插入操作叫做压栈,也成为入栈、进栈。插入的数据在栈顶。
出栈:栈的删除操作叫做出栈。需要出栈的数据也是在栈顶。
栈的实现
栈的实现一般可以使用数组或者链表实现。相对而言,用数组实现栈要简单一些,因为数组尾插比较简单,而单链表尾插需要找尾。
和顺序表一样,栈也有静态栈和动态栈。下面实现以下动态栈。
代码如下:
void STInit(ST* pst)
{
/*ST* tmp = (ST*)malloc(sizeof(ST));
if (tmp == NULL)
{
perror("malloc");
return;
}*/
pst->a = NULL;
pst->top = -1;
pst->capacity = 0;
}
void STPush(ST* pst, int x)
{
assert(pst);
if (pst->top == pst->capacity - 1)
{
int newcapacite = pst->capacity == 0 ? 4 : pst->capacity * 2;
int* tmp = (int*)realloc(pst->a, newcapacite * sizeof(int));
if (tmp == NULL)
{
perror("realloc");
return;
}
pst->a = tmp;
pst->capacity = newcapacite;
}
pst->a[pst->top + 1] = x;
pst->top++;
}
void STPop(ST* pst)
{
assert(pst);
pst->top--;
}
int STTop(ST* pst)
{
assert(pst);
if (pst->top == -1)
{
printf("此栈为空");
return 1;
}
return pst->a[pst->top];
}
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == -1;
}
int STSize(ST* pst)
{
assert(pst);
return pst->top++;
}
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = 0;
pst->top = -1;
}
写下来发现还是很好写的。不过要注意栈顶top的初始取值,如果是-1的话,就是跟着数组的下标走的,如果是0的话,就是数组下标+1.
队列
队列的概念和结构
队列只允许在一端进行插入数据的操作,在另一端进行删除数据的特殊的线性表。队列是先进先出(First In First Out)。
队尾:像排队一样,数据插入的一端称为队尾。
队头:删除数据的一端称为队头。
队列的实现
和栈一样,队列也可以用数组和链表的结构实现。用链表实现比较简单一些,因为链表头删比较简单。
代码如下:
void QueueInit(Queue* pq)
{
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
void QueuePush(Queue* pq, int x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc");
return;
}
newnode->val = x;
newnode->next = NULL;
if (pq->ptail == NULL)
{
pq->ptail = pq->phead = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
pq->size++;
}
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->phead);
Queue* del = pq->phead;
pq->phead = pq->phead->next;
free(del);
if (pq->phead == NULL)
pq->ptail = NULL;
pq->size--;
}
int QueueFront(Queue* pq)
{
assert(pq);
assert(pq->phead);
return pq->phead->val;
}
int QueueBack(Queue* pq)
{
assert(pq);
assert(pq->ptail);
return pq->ptail->val;
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->phead = NULL;
}
int QueueSize(Queue* pq)
{
assert(pq);
return pq->size;
}
void QueueDestroy(Queue* pq)
{
assert(pq);
QNode* cur = pq->phead;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
有没有发现队列的头删特别简单,尾插也很简单,嘻嘻。
今天就到这里了捏!