添加计算栈元素个数操作
时间: 2024-01-13 15:05:47 浏览: 27
计算栈元素个数的操作可以通过遍历链表中的元素并计数来实现。具体实现方法可以从栈顶元素开始,依次遍历链表中的每个元素,并在每个节点上计数,直到链表的末尾。
下面是一个计算栈元素个数的示例代码:
```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 size(Stack* s) {
int count = 0;
Node* current = s->top;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int main() {
Stack* s = createStack();
push(s, 1);
push(s, 2);
push(s, 3);
traverse(s);
printf("Size of stack: %d\n", size(s));
printf("%d\n", pop(s));
printf("%d\n", pop(s));
traverse(s);
push(s, 4);
traverse(s);
printf("Size of stack: %d\n", size(s));
return 0;
}
```
在该代码中,我们添加了一个`size`函数,用于计算栈中元素的个数。在该函数中,我们在遍历链表中的每个元素时对计数器`count`进行加一操作。最后,我们返回计数器的值。
在main函数中,我们在程序中间和结束时分别调用`size`函数来计算栈中元素的个数,并将结果打印到屏幕上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)