使用链表进行堆栈弹出操作

Stack pop operation using linked list

本文关键字:操作 堆栈 链表      更新时间:2023-10-16

列表中的元素是 6495,即前 5 个被推送,然后推送 9,依此类推。现在我想弹出 5(我知道前 6 应该根据 FILO),即以相反的顺序。在我第一次和第二次进行弹出操作时弹出的元素都是 5。Temp 是一个局部变量,所以即使我在 pop 函数中释放它,如果我要在 main 中显示元素,它也不会在 main 中释放?这是真的吗?但无论如何,我在流行操作本身中做了我的 cout,但它仍然不起作用?如果我在弹出后使用显示 fn,它会进入无限循环。

#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct stackNode
{
int data;
struct stackNode *next;
};
int is_emp(struct stackNode* head)
{
if(head==NULL)
    return 0;
else
    return 1;
}
void push(struct stackNode** head,int data)
{
struct stackNode* current =(struct stackNode*)malloc(sizeof(struct stackNode));
current->data=data;
current->next=NULL;
current->next=*head;
*head=current;
}
int pop(struct stackNode** head)
{
    int ele;
    struct stackNode* temp=*head;
    if(is_emp(*head)==NULL)
    {
        cout<<"Underflow";
        return INT_MIN;
    }
    else
    {
     while(temp->next!=NULL)
    {
    temp=temp->next;
    }
  cout<<"Popped ele:"<<temp->data<<endl;
  free(temp);
  temp=NULL;   
 }
}
void disp(struct stackNode* head)
{
    while(head!=NULL)
    {
        cout<<head->data<<endl;
        head=head->next;
    }
}
int main()
{
    struct stackNode* head=NULL;
    push(&head,5);
    push(&head,9);
    push(&head,4);
    push(&head,6);
    disp(head);
    pop(&head);
    disp(head);
    return 0;
}
if(temp!=NULL)
{
    ele=temp->data;
    temp=temp->next;
}
free(temp);

在这里,您正在使用临时变量而不是头部进行更改。因此,当您在 main 中看到它时,头部指针仍然指向 6。

在头部指针中进行更改,而不是临时指针。

我认为这是您期待的代码。请注意引用的使用。

#include <limits>
struct stackNode
{
    stackNode *next;
    int data;
    stackNode(stackNode *n, int d) : next(n), data(d) {}
};
void push(stackNode* &head,int data)
{
    head =new stackNode(head, data);
}
int pop(stackNode* &head)
{
    if (head == NULL) {
       return std::numeric_limits<int>::min();
    } else {
        int ret = head -> data;
        stackNode *temp = head;
        head = head->next;
        delete temp;
        return ret;
    }
}
int main()
{
    stackNode* head = NULL;
    push(head,5);
    push(head,9);
    push(head,4);
    push(head,6);
 //   disp(head);
    pop(head);
//    disp(head);
    return 0;
}