在链表中实现推送/弹出(C ++)

时间:2011-09-24 12:18:28

标签: c++ stack linked-list implementation

我正在尝试将push / pop合并到一个链表中,我似乎无法让它工作。当我运行我的测试功能时,我将链接列表设置为零,我尝试推送值,但列表会一直返回而没有值。有谁可能告诉我我做错了什么?

7 个答案:

答案 0 :(得分:1)

if (top == NULL){
      current = top;
      current->next = NULL; //NULL->next : will cause segfault
  }

如果top为NULL,则设置current = top [为NULL],然后访问current->next,这将导致段错误,您尝试访问NULL ..

编辑:跟进评论: 你的if语句看似多余,你应该只需要设置:current->next = head;head = current; [除了当前的分配]

答案 1 :(得分:0)

而不是

 if (top == NULL){
      current = top;
      current->next = NULL;
 }

你想要

 if (top == NULL){
      top = current;
      current->next = NULL;
 }

当然,在此之后,您必须确保再次将head设置为top

既然你已经做了这个改变,那么两个案例都应该做同样的事情 - 因此实际上不需要区分案例。所以函数可以简化为

void push(Data * newPushData){
    LinkNode * current = new LinkNode(newPushData);
    current->next = head;
    head = current;
}

答案 2 :(得分:0)

top变量是push(...)函数的局部变量。您可以改为使用head,而我宁愿修改if语句。

我认为该功能应如下所示:

void push(Data * newPushData){
    LinkNode * current = new LinkNode(newPushData);
    if (head != NULL){
        current->next = head;
        head = current;
    }
    else{
        head = current;
        current->next = NULL; // if you haven't done it in LinkNode constructor
    }
}

答案 3 :(得分:0)

void push(Data * newPushData)
{
    if( head != NULL )
    {
        LinkNode current = new LinkNode(newPushData);
        current->next = head;
        head = current;
    }
    else
    {
        head = new LinkNode(newPushData);
    }
}

答案 4 :(得分:0)

请指定链表类的属性吗? [你有什么可能做错了吗]

而不是你,我会这样做:

void push(Data * newPushData){
if (head   == NULL) 
    head->data = newPushData
    tail = head ; 

else // regular situation 
     { 
     Node  * node  = new Node() ; 
     tail->next = node; 
     node->data  = newPushData; 
     node->next  = NULL ;
     tail  = node ; 
   } 

}

在链表中你必须保持列表头部的头指针点,保持尾指针指向列表尾部, 您必须处理扩大列表的2个案例。 学习的最佳方式是说明空白链表上的插入。

保重 S

答案 5 :(得分:0)

试试这段代码......

void push(data * newpushdata){
    if(head !=null){
        linkednode current = new linkednode(newpushdata);
        current->next = head;
        head = current;
    }
    else {
       head = new linkednode(newpushdata);
    }
}

答案 6 :(得分:0)

这是我对包含int元素的Stack的工作解决方案,但也许最好使用Stack ** S而不是Stack * S创建void pushStack。

pop中的

(Stack ** S)我创建了一个sentinel,所以如果堆栈为空,则返回-1。:

typedef struct StackT {

    int val;
    struct StackT *next;

} Stack;

int isStackEmpty (Stack *S) {

    if (S == NULL)
        return 1;
    else
        return 0;
}


int *pop(Stack **S) {
    Stack *tmp = *S;
    int i = -1;
    if (isStackEmpty(tmp) == 0) {
        i = tmp->val;
        *S = tmp->next;
    }
    return i;
}

Stack *pushStack (Stack *S, int x) {

    Stack *node = (Stack *) malloc (sizeof (Stack));
    node->val = x;
    node->next = S;

    return node;
}

你可以轻松调用pop和stack:

    Stack *S = NULL;
    int x = somevalue;
    int y;
    S = pushStack(S, x);
    y = pop(&S);