使用链接列表进行堆栈实现

时间:2011-03-08 03:39:03

标签: c stack linked-list

这是我的链接列表的堆栈实现。该程序工作正常。您对功能/性能/内存使用情况有何评论?

#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);
    }

}

2 个答案:

答案 0 :(得分:3)

您的代码中存在无数问题。在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
        }
    }`

您实际在做的是将新创建的节点插入到链接列表的末尾。这有点是通过链接列表实现的队列

答案 1 :(得分:0)

实现相同的一种方法是在链接中完成 http://codepad.org/dRMwSOuO
其中一个新项目被添加到列表的初始端并从同一端开始。虽然边界条件没有正确处理。但是时间复杂度会更好,因为你不必在列表中遍历直到结束。