2011-09-24 145 views
0

我試圖將push/pop合併到鏈表中,我似乎無法使其工作。當我運行我的測試函數時,我將鏈接列表設置爲零,並嘗試推送值,但列表一直返回而沒有任何值。誰能告訴我我做錯了什麼?在鏈表中實現push/pop(C++)

回答

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

如果頂部爲NULL,則設置current = top [這是NULL],然後訪問current->next,這將導致一個段錯誤,您試圖訪問NULL ..

編輯:跟隨高達評論:
你的if語句似乎是多餘的,你應該只需要設置:current->next = head;head = current; [除了當前分配]

+0

我從top = current改變了它,但是我仍然沒有得到任何回報。 – BleuCheese

+2

@BleuCheese:問題在於當你需要改變全局變量'head'時,你只改變局部變量'top' - 否則,你的改變不會在函數結束後「生存」 。 –

+0

你的if語句似乎是多餘的,你應該只需要設置:'current-> next = head;'和'head = current;' – amit

0

而不是

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

}

在你不得不在維持頭指針指向一個鏈表該列表的頭部,保持尾部指針位於列表的尾部, 您必須注意擴大列表的兩種情況。 學習的最佳方式是說明在空白鏈表上的插入。

照顧 小號

0

試試這個代碼...

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

這只是一堆代碼。請至少發表評論 – kolossus

0

是含有INT元素堆棧我工作的解決方案,但也許這是更好地創建使用堆棧的空隙pushStack ** S而不是Stack * S。

在彈出(棧** 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; 
} 

你可以叫流行音樂和伊斯利堆棧:

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