数据结构之栈的链表实现
代码:
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
//链表节点定义
typedef struct node
{
int value;
struct node* next;
}Node;
//入栈操作
bool push(Node** head, int val)
{
if (*head == NULL)
{
*head = (Node*)malloc(sizeof(Node));
printf_s("Pushing %d\n", val);
(*head)->value = val;
(*head)->next = NULL;
return true;
}
Node *temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = (Node*)malloc(sizeof(Node));
printf_s("Pushing %d\n", val);
temp->next->value = val;
temp->next->next = NULL;
return true;
}
//出栈操作
bool pop(Node** head)
{
if (*head == NULL)
{
printf_s("Stack is empty!!!\n");
return true;
}
if ((*head)->next == NULL)
{
printf_s("Poping %d\n", (*head)->value);
free(*head);
*head = NULL;
return true;
}
Node *temp = *head;
while (temp->next->next)
{
temp = temp->next;
}
printf_s("Poping %d\n", temp->next->value);
free(temp->next);
temp->next = NULL;
return true;
}
//链表遍历操作
void traverse(Node* head)
{
if (head == NULL)
{
printf_s("Stack is empty!!!\n");
return;
}
printf_s("Traversing: ");
while (head)
{
printf_s("%d\t", head->value);
head = head->next;
}
printf_s("\n");
}
//销毁链表操作
bool destruct(Node **head)
{
if (*head == NULL)
{
printf_s("Stack is empty!!!\n");
return true;
}
Node **bottom = head;
Node *cur = *head;
Node *temp = NULL;
while (cur)
{
temp = cur;
printf_s("Destructing %d\n", temp->value);
cur = cur->next;
free(temp);
}
*bottom = NULL;
return true;
}
int main()
{
Node *stack = NULL;
int n = 10;
for (int i = 0; i < n; ++i)
{
push(&stack, i);
traverse(stack);
}
printf_s("stack = %p\n", stack);
for (int i = 0; i < n; ++i)
{
pop(&stack);
traverse(stack);
}
destruct(&stack);
printf_s("stack = %p\n", stack);
return 0;
}
运行结果:
参考:
C程序设计(第四版)谭浩强