C語言指標實現簡單棧
阿新 • • 發佈:2019-01-07
stack:FILO
操作:push 向棧頂壓入一個元素
pop 從棧頂彈出元素,pop一個空棧返回-1
節點結構體:
typedef struct _node
{
int data;
struct _node *next;
} Node;
棧結構體:
typedef struct linkedlist
{
Node *head;
Node *tail;
} Stack;
操作:
//初始化棧
void initializeStack(Stack *stack)
{
stack->head = NULL;
stack ->tail = NULL;
}
//向棧頂壓入元素
void push(Stack *stack, int data)
{
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
if (stack->head == NULL)
{
stack->tail = node;
node->next = NULL;
}
else
{
node->next = stack->head;
}
stack ->head = node;
}
//彈出棧頂元素並返回棧頂元素的值
int pop(Stack *stack)
{
int data;
Node *node = stack->head;
if (stack->head == NULL)
{
data = -1;
}
else if (node == stack->tail)
{
data = stack->head->data;
stack->head = stack->tail = NULL ;
free(node);
}
else
{
data = stack->head->data;
stack->head = stack->head->next;
free(node);
}
return data;
}
//釋放所有未釋放的空間
void freeAll(Stack *stack)
{
while(pop(stack)!=-1);
printf("\nFree Complete!\n");
return;
}
int main()
{
Stack stack;
initializeStack(&stack);
push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
push(&stack, 4);
push(&stack, 5);
printf("%d ", pop(&stack));
printf("%d \n", pop(&stack)); //5 4
//1 2 3 <- top
push(&stack, 11);
push(&stack, 23);
push(&stack, 323); //1 2 3 11 23 323
printf("%d ", pop(&stack));
printf("%d ", pop(&stack));
printf("%d ", pop(&stack));
printf("%d ", pop(&stack));
printf("%d ", pop(&stack));
printf("%d ", pop(&stack));
printf("%d \n", pop(&stack));
freeAll(&stack);
return 0;
}
小結:棧的實現基於連結串列,push操作相當於addHead