添加遍历栈中元素操作
时间: 2023-08-24 21:15:43 浏览: 70
遍历栈中元素的操作可以通过循环遍历链表中的元素来实现。具体实现方法可以从栈顶元素开始,依次遍历链表中的每个元素,直到链表的末尾。
下面是一个遍历栈中元素的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
typedef struct stack {
Node* top;
} Stack;
Stack* createStack() {
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = NULL;
return s;
}
void push(Stack* s, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = s->top;
s->top = n;
}
int pop(Stack* s) {
if (s->top == NULL) {
printf("Stack is empty!\n");
return -1;
}
int data = s->top->data;
Node* temp = s->top;
s->top = s->top->next;
free(temp);
return data;
}
void traverse(Stack* s) {
Node* current = s->top;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Stack* s = createStack();
push(s, 1);
push(s, 2);
push(s, 3);
traverse(s);
printf("%d\n", pop(s));
printf("%d\n", pop(s));
traverse(s);
push(s, 4);
traverse(s);
return 0;
}
```
在该代码中,traverse函数用来遍历栈中的元素,依次输出链表中每个元素的值。在main函数中,先将元素1、2、3入栈,在遍历栈中元素。然后依次出栈并打印出栈的元素,并在每次操作后再次遍历栈中元素。最后将元素4插入栈中,并再次遍历栈中元素。