2017-04-19 24 views
-2

我試圖找出如何而定創建一個功能,增加了一個新的節點到堆棧的頂部:推送功能(添加新節點列表的頂部)C++

// a structure for a node 
struct node { 
int key; 
node * next; 
}; 

// a structure for a stack 
struct stack { 
node * top; 
node * bottom; 
}; 

// and the function declaration 
void push(stack & s, int key) 

據推測爲空堆棧和超過1個節點的堆棧工作。

我真的很難理解指向結構的指針是如何工作的以及如何添加和刪除它們,所以任何解釋都將不勝感激。謝謝!

+1

這看起來像一個單獨鏈接列表實現的堆棧。瞭解鏈表的最好方法之一是將吸盤吸引在一張紙上,觀察節點如何互連以製作有意義的列表。一旦你可以看到必須發生的事情,其餘的事情變得更容易。 – user4581301

+0

使用C++的列表容器http://www.cplusplus.com/reference/list/list/ – RomMer

回答

0

s是一個指向堆棧的指針,它有兩個值,即'bottom'和'top',top是堆棧的屬性,但bottom應該是堆棧的起始指針(鏈表的形式)

void push(stack *s, int key) 
{ 
    struct node newNode; 
    newNode.key = key; 
    newNode.next = NULL; 

    if(s->top == NULL) 
    { 
     s->top =&newNode; 
     s->bottom =&newNode; 
    } 
    else{ 
    //Assigning new node to top 
    s->top->next = &newNode; 

    //pointing top to new node 
    s->top = &newNode; 
    } 
} 

檢查出來。