【问题标题】:Stack pop operation using linked list使用链表的堆栈弹出操作
【发布时间】:2014-12-29 09:54:03
【问题描述】:

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

【问题讨论】:

  • 为什么在 C++ 代码中使用free?您为什么不使用其中一种标准模板来执行此操作?
  • @EdHeal 它不会引起任何问题。(也不是警告)。那我应该用什么?
  • @Rooney10 至少你没有分配任何东西,那么free()'d 应该在那里?
  • @Rooney10 new/delete 用于 C++,malloc/free 用于 C
  • @πάνταῥεῖ 没错,但我应该用什么来代替免费。问题出在空闲部分,temp 是一个局部变量,我们也没有为它分配任何内存,但是使用 temp 作为全局变量,我得到的输出也不正确,所以问题一定出在空闲部分

标签: c++ singly-linked-list


【解决方案1】:
if(temp!=NULL)
{
    ele=temp->data;
    temp=temp->next;
}
free(temp);

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

在 head 指针中进行更改,而不是 temp。

【讨论】:

  • 是的,但我不能使用 *head 代替 temp 在这种情况下,链表将丢失。我正在使用 temp 遍历最后一个元素,即 5 来释放它,但由于它是一个局部变量,因此更改不会反映在外部。我不知道用什么代替 temp
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 2012-10-14
    • 1970-01-01
    • 2014-12-18
    • 2014-11-30
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多