这是我用链表实现的栈。该程序运行正常。您对功能/性能/内存使用有何评论?
#include <stdafx.h>
#include <stdlib.h>
#include <stdio.h>
struct node
{
int data;
struct node * next;
};
int length(struct node * current)
{
int len = 0;
while(current)
{
len++;
current = current->next;
}
return len;
}
struct node* push(struct node* stack, int data)
{
struct node * current = stack;
struct node * newNode = (node*)(malloc(sizeof(node*)));
newNode->data = data;
newNode->next = NULL;
//length(current);
//single element case
if(stack == NULL)
{
stack = newNode;
}
else// multiple element case
{
while(current!=NULL)
{
if(current->next==NULL){
current->next = newNode;
break;
}
else
{
current = current->next;
}
}
}
return stack;
}
bool isemp(struct node * stack)
{
if(stack == NULL)
{
printf("Stack is empty");
return true;
}
else{
return false;
}
}
struct node * pop(struct node * stack)
{
struct node * current = stack;
struct node * previous = NULL;
bool isempty = false;
while(!isemp(stack)&& current)
{
if(current->next==NULL)
{
//delete previous;
if(previous)
{
previous->next = NULL;
printf("Popped element is %d ", current->data);
current = current->next;
}
else if(length(stack)==1)
{
printf("Pop last element %d",stack->data);
stack = NULL;
current = NULL;
}
}
else
{
previous = current;
current = current->next;
//stack = current;
}
}
return stack;
}
void main()
{
struct node * stack = NULL;
int data = 1;
int index = 5;
while(index)
{
stack = push(stack,data );
data++;
index--;
}
while(stack!=NULL)
{
stack = pop(stack);
}
}
最佳答案
您的代码中存在无数问题。在 push() 方法中您这样做:
while(current!=NULL)
{
if(current->next==NULL){
current->next = newNode; //This is also Wrong .You are not making Head pointing to newly created node
break;
}
else
{
current = current->next; //This is Wrong For Stack Implementation
}
}`
您实际上在做的是将一个新创建的节点插入到链表的末尾。因此有点像通过链表实现的队列。
关于c - 用链表实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5228041/