[Cpp]
// Use a linked list to build a stack.
// Input 1 2 3 4 5 0 output 5 4 3 2 1
# Include <stdio. h>
# Include <stdlib. h>
# Define true 1
# Define false 0
Typedef struct node {// create a struct
Int num;
Struct node * next;
} Node;
Int push (Node ** head, int num) // press a number into the stack with the head as the header
{
Node * nextNode;
If (NULL = (nextNode = (struct node *) malloc (sizeof (struct node )))){
Return false;
}
NextNode-> num = num;
If (NULL = * head ){
NextNode-> next = NULL;
* Head = nextNode;
Return true;
}
NextNode-> next = * head; // end Insertion Method
* Head = nextNode;
Return true;
}
Int pop (Node ** head, int * num) // output Stack
{
Node * temp;
If (NULL = * head) return false;
* Num = (* head)-> num;
Temp = (* head)-> next;
Free (* head );
* Head = temp;
Return true;
}
Int main (int argc, char * argv []) // main Function
{
Int n = 0, num;
Node * head;
Head = NULL;
Printf ("Please input numbers end with 0: \ n ");
While (1) {// if not 0, press the stack
Scanf ("% d", & num );
If (0 = num) break;
Push (& head, num );
N ++;
}
While (pop (& head, & num) {// output of the output Stack
Printf ("% d", num );
}
Printf ("\ nTotal: % d \ n", n );
}
Author: CreazyApple