2014-10-08 53 views
1

我想弄清楚堆棧鏈表的方式。我找到了一種方法,但這種方法只適用於陣列工作棧空堆棧的鏈表

void empty(StackPtr S) 
{ 
    S -> top = -1; 
} 

我的猜測是使用

while(!isEmpty(s)) 

該函數的isEmpty將檢查堆棧是否爲空。然後我卡:(

編輯: 我把它的方式:。

void push(StackPtr S, StackData d) /*adds the top element*/ 
{ 
    NodePtr np = (NodePtr)malloc(sizeof(Node)); 
    np -> data = d; 
    np -> next = S -> top; 
    S -> top = np; 

} 
+0

你是如何將物品推入堆棧的嗎?你是否編碼過一種方式將它們彈出來? – polarysekt 2014-10-08 04:13:45

+0

嗨,我已將它添加到上面:) – kybookie 2014-10-08 04:26:03

+1

'isEmpty()'可以檢查(或替換爲支票)如果'top'是一個無效指針。如果沒有,請保持'pop()'pin'直到它,確保free()'每一個。 – polarysekt 2014-10-08 04:34:25

回答

2

這是實現堆棧數據結構及其操作的基本程序希望這將有助於你

#include<stdio.h> 
#include<stdlib.h> 
#define INT_MIN -99; 

struct Stack{ 
    int data; 
    struct Stack *next; 
}; 

struct Stack *CreateStack(){ 
    return NULL; 
} 

void Push(struct Stack **top,int data){ 
    struct Stack *temp; 
    temp=malloc(sizeof(struct Stack)); 

    if(!temp) 
     return NULL; 

    temp->data = data; 
    temp->next= *top; 

    *top=temp; 
} 

int IsEmptyStack(struct Stack *top){ 
    return top==NULL; 
} 

int Pop(struct Stack **top){ 
    int data; 
    struct Stack *temp; 

    if(IsEmptyStack(*top)) 
     return INT_MIN; 

    temp=*top; 
    *top=temp->next; 
    data=temp->data; 
    printf("%d",data); 
    free(temp); 
    return data; 
} 

int Top(struct Stack *top){ 
    if(IsEmptyStack(top)) 
     return INT_MIN; 

    return top->next->data; 
} 

void DeleteStack(struct Stack **top) 
{ 
    struct Stack *temp,*p; 
    p=*top; 
    while(p->next){ 
     temp=p->next; 
     p->next=temp->next; 
     free(temp); 
    } 

    free(p); 
} 

void main(){ 

    struct Stack *s=CreateStack(); 
    Push(&s,5); 
    Push(&s,15); 
    Push(&s,52); 
    Pop(&s); 
    Pop(&s); 
    Push(&s,35); 
    Push(&s,53); 
    Pop(&s); 
    Push(&s,45); 

}