[数据结构]链栈的创建,入栈和出栈

栈是一种在栈顶压入和弹出的数据结构,所以只在一端进行操作.为了减小遍历开支,所以链栈一般在首元节点处进行插入(入栈).

#include 
#include 


typedef struct Node {
    int data;
    struct Node* next;

}Node;
Node* pushStack(Node* , int); 
void print_Stack(Node* );
Node* popStack(Node* ptr,int* popvalue);
int main() 
{
    Node* ptr = NULL; 
    int value = 0,popvalue=0;

    /*数据进行入栈*/
    for (int i = 0; i < 10; i++) {
        value = 10 * i + 10;
        ptr=pushStack(ptr, value);
    }
    print_Stack(ptr);    
    ptr=popStack(ptr,&popvalue);
    printf("popvalue=%d\n",popvalue);
    print_Stack(ptr);
    
    return 0;
}
/*执行压栈操作*/
Node* pushStack(Node* ptr, int pushvalue) 
{
    if (ptr == NULL)
    {
        Node* newNode = (Node*)malloc(sizeof(Node));
        ptr = newNode; newNode->next = NULL; newNode->data = pushvalue;
    }
    else {
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = pushvalue;
        newNode->next = ptr;
        ptr = newNode;
    }
    return ptr;
}

void print_Stack(Node* ptr)
{
    Node* str=ptr;
    while (str->next!=NULL) 
    {
        printf("%d\n", str->data);
        str = str->next;
    }
    printf("%d\n", str->data);
}
/*执行出栈操作*/
Node* popStack(Node* ptr,int* popvalue)
{    
    Node* delete_ptr=NULL;
    *popvalue=ptr->data;
    delete_ptr=ptr;
    ptr=ptr->next;
    free(delete_ptr);
    delete_ptr=NULL;    
    return ptr;
}

 出栈返回栈顶数据代码:

#include 
#include 


typedef struct Node {
    int data;
    struct Node* next;
}Node;
Node* pushStack(Node* , int); 

void print_Stack(Node* );
int popStack(Node** ptr,int popvalue);

int main() 
{
    Node* ptr = NULL; 
    int value = 0,popvalue=0;
    /*数据进行入栈*/
    for (int i = 0; i < 10; i++) {
        value = 10 * i + 10;
        ptr=pushStack(ptr, value);
    }
    print_Stack(ptr);    
    popvalue=popStack(&ptr,popvalue);
    printf("popvalue=%d\n",popvalue);
    print_Stack(ptr);
    return 0;
}

/*执行压栈操作*/
Node* pushStack(Node* ptr, int pushvalue) 
{
    if (ptr == NULL)
    {
        Node* newNode = (Node*)malloc(sizeof(Node));
        ptr = newNode; 
        newNode->next = NULL;
        newNode->data = pushvalue;
    }
    else {
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = pushvalue;
        newNode->next = ptr;
        ptr = newNode;
    }
return ptr;
}

void print_Stack(Node* ptr)
{
    Node* str=ptr;
    while (str->next!=NULL) {
        printf("%d\n", str->data);
        str = str->next;
    }
    printf("%d\n", str->data);
}

/*进行出栈操作*/
int popStack(Node** ptr,int popvalue)
{   
    Node* delete_ptr=NULL;
    popvalue=(*ptr)->data;
    delete_ptr=*ptr;
    *ptr=((*ptr)->next);
    free(delete_ptr);
    delete_ptr=NULL;    
    return popvalue;
}

修改为具有头指针的形式

你可能感兴趣的:(数据结构)