c - 用链表实现堆栈

标签 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);
    }

}

最佳答案

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

相关文章:

c - 在 Oracle Linux 7.2 上编译 C 代码时出错

不同操作系统上的python ctypes问题

python - 使用堆栈评估中缀表达式时出现算术错误评估和 KeyDict 错误;

c++ - 堆栈和队列回文程序

c - 如何使用 C 结构中的字符串字段?

c++ - C++遍历单向链表

c - 如何在外部文件中读取前n个结构变量的数量-C

c - 作为父进程运行子进程

c - 我使用了多少堆栈内存? <C>

c++ - 删除 LinkedList 中的前面元素会产生垃圾