棧2: 鏈式儲存

HIK4RU44發表於2024-04-18

棧2: 棧的鏈式儲存


棧的結點

//鏈式棧的結點
typedef struct LINKNODE{
    struct LINKNODE *next;
} LinkNode;

鏈式棧的結構

//鏈式棧
typedef struct LINKSTACK{
    LinkNode head;
    int size;
} LinkStack;

棧的初始化

LinkStack* Init_LinkStack(){
    LinkStack *stack = (LinkStack*)malloc(sizeof(LinkStack));
    stack->head.next = NULL;
    stack->size=0;
    //返回棧頂
    return stack;
};

入棧(頭插法)

//棧是先進後出, 頭插法更加適合
void Push_LinkStack(LinkStack* stack, LinkNode *data){
    if(stack==NULL) return;
    if(data==NULL) return;
    data->next = stack->head.next;
    stack->head.next = data;
    stack->size++;
};

返回棧頂元素

LinkNode* Top_LinkStack(LinkStack* stack){
    if(stack==NULL) return NULL;
    if(stack->size==0) return NULL;
    return stack->head.next;
};

出棧(刪除第一個元素)

void Pop_LinkStack(LinkStack* stack){
    if(stack==NULL) return;
    if(stack->size==0) return;    
    LinkNode *curNode = stack->head.next;

    stack->head.next =  stack->head.next->next;
    curNode->next = NULL;
    free(curNode);

    stack->size--;
};

返回棧元素個數

int Size_LinkStack(LinkStack* stack){
    if(stack==NULL) return -1;
    return stack->size;
};

清空

void Clear_LinkStack(LinkStack* stack){
    if(stack==NULL) return;
    stack->head.next = NULL;
    stack->size = 0;
};

銷燬

void FreeSpace_LinkStack(LinkStack* stack){
    if(stack==NULL) return;
    free(stack);
};

測試

自定義棧結構

typedef struct PERSON{
    LinkNode node;    
    char name[64];
    int age;
} Person;

測試

int main(){
    //初始化棧
    LinkStack *stack = Init_LinkStack();
    //建立資料
    Person p1,p2,p3;
    //strcpy(char *dest, const char *src) 把 src 所指向的字串複製到 dest。
    strcpy(p1.name, "aaa");
    strcpy(p2.name, "bbb");
    strcpy(p3.name, "ccc");
    p1.age = 10;
    p2.age = 20;
    p3.age = 30;
    //入棧
    Push_LinkStack(stack, (LinkNode*)&p1); //進行型別的強制轉換
    Push_LinkStack(stack, (LinkNode*)&p2);
    Push_LinkStack(stack, (LinkNode*)&p3);
    //輸出
    while(Size_LinkStack(stack)>0){
        //取出棧頂元素
        Person *p = (Person*)Top_LinkStack(stack);
        cout << p->name << " " << p->age << endl;
        //彈出棧頂元素
        Pop_LinkStack(stack);
    }
    //銷燬棧
    FreeSpace_LinkStack(stack);


    system("pause");
    return 0;
}

相關文章