Вот моя реализация стека со связанным списком. Программа работает правильно. Хотели бы вы прокомментировать функциональность / производительность / использование памяти?
#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);
}
}