這是我的鏈接列表實現。該程序正常工作。你會在功能/性能/內存使用方面有任何意見嗎?使用鏈接列表實現堆棧實現
#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);
}
}
無法讀取...修復您的代碼格式。 – andersoj 2011-03-08 03:42:40
這個問題是不是更適合http://codereview.stackexchange.com/? – Pablo 2011-03-08 03:44:15
目前還沒有'codereview屬於'... – 2011-03-08 03:47:11