2014-10-08 51 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); 

}