簡體   English   中英

在鏈表中實現推/彈出(C ++)

[英]Implementing push/pop in a linked list (C++)

我正在嘗試將push / pop合並到鏈接列表中,但似乎無法正常工作。 當我運行測試函數時,我將鏈接列表設置為零,並嘗試推送值,但是列表不斷返回而其中沒有任何值。 誰能告訴我我在做什么錯?

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; [除了當前分配之外]

這是我對包含int元素的Stack的工作解決方案,但也許最好使用Stack ** S而不是Stack * S創建一個無效的pushStack。

在pop(Stack ** S)中,我創建了一個哨兵,因此如果堆棧為空,則返回-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);

代替

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

你要

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

,當然,在這之后,你必須確保你實際設置headtop一次。

既然您已經進行了更改,那么很明顯兩個案例都做同樣的事情-因此實際上不需要區分大小寫。 所以功能可以簡化為

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

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
    }
}
void push(Data * newPushData)
{
    if( head != NULL )
    {
        LinkNode current = new LinkNode(newPushData);
        current->next = head;
        head = current;
    }
    else
    {
        head = new LinkNode(newPushData);
    }
}

您可以指定鏈接列表類的屬性嗎? [您做錯事的機會很小]

代替您,我會:

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

}

在鏈接列表中,必須將頭指針指向列表的頭部,並確保尾部指針指向列表的尾部,您必須注意兩種放大列表的情況。 最好的學習方法是說明在空白鏈表上的插入。

保重S

試試這個代碼...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM