使用链表实现堆栈。我哪里错了?

时间:2014-12-04 19:17:32

标签: c linked-list stack singly-linked-list

这是我用C编写的代码:

#include<stdio.h>
struct Node
{
    int info;
    struct Node *next;
};
void init_Node(struct Node *n)
{
    n->next = NULL;
}
struct Node *front = NULL;
void display()
{
    struct Node *rear = front;
    if(rear == NULL)
        printf("List is empty!\n");
    else
    {
        printf("[%i]-->",rear->info);
        rear = rear->next;
    }
    printf("NULL");
    printf("\n");
}
void addEnd(int x)
{
    struct Node *n = malloc(sizeof(struct Node));
    struct Node *rear = front;
    n->info = x;
    if(front == NULL)
        front = n;
    else
    {
        while(rear->next != NULL)
            rear = rear->next;
        rear->next = n;
        rear = n;
    }
    display();
}
void deleteEnd()
{
    struct Node *rear = front;
    if(front == NULL)
        printf("Stack is Empty!");
    else
    {
        while(rear->next->next != NULL)
        {
            rear = rear->next;
        }
        printf("Popped : %i\n", rear->next->info);
        rear->next = NULL;
        display();
    }
}
int main()
{
    struct Node *n = malloc(sizeof(struct Node));
    init_Node(n);
    clrscr();
    addEnd(23);
    addEnd(45);
    addEnd(8);
    addEnd(57);
    deleteEnd();
    addEnd(98);
    deleteEnd();
    getch();
    return 0;
}

以下输出是使用类在C ++中完成实现时的输出。 程序的输出应该是这个 -

enter image description here

但我的代码输出是这样的 - enter image description here

修改 添加while()循环并添加n-&gt; next = NULL;输出结果如下: enter image description here

我哪里错了?

2 个答案:

答案 0 :(得分:3)

您需要进行两项更改:

void display()
{
    struct Node *rear = front;
    if(rear == NULL)
        printf("List is empty!\n");
    else
    {
        // CHANGE 1: You need a while loop here
        while(rear != NULL) {
            printf("[%i]-->",rear->info);
            rear = rear->next;
        }
    }
    printf("NULL");
    printf("\n");
}

void addEnd(int x)
{
    struct Node *n = malloc(sizeof(struct Node));
    struct Node *rear = front;
    n->info = x;
    // CHANGE 2: You need to clear n->next to NULL.
    n->next = NULL;
    if(front == NULL)
        front = n;
    else
    {
        while(rear->next != NULL)
            rear = rear->next;
        rear->next = n;
        rear = n;
    }
    display();
}

答案 1 :(得分:0)

在你的函数中,addEnd()需要将下一个指针初始化为零。所以,就在行n-> info = x之后;添加一行n-> next = 0;