-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList_stack.c
More file actions
84 lines (76 loc) · 1.54 KB
/
Copy pathlinkedList_stack.c
File metadata and controls
84 lines (76 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node{
int value;
Node* next;
};
Node* createNode(int value);
Node* push(Node* head, int x);
int pop(Node** head);
int top(Node* head);
void traverse(Node* head);
int main(){
int firstV;
printf("please input the first element of the stack:");
scanf("%ld",&firstV);
Node* head = createNode(firstV);
head = push(head,5);
traverse(head);
head = push(head,10);
traverse(head);
head = push(head,15);
traverse(head);
head = push(head,3);
traverse(head);
printf("%ld\n",pop(&head));
traverse(head);
printf("%ld\n", top(head));
traverse(head);
}
Node* createNode(int data){
Node* node = (Node*)malloc(sizeof(Node));
node->value = data;
node->next = NULL;
return node;
}
Node* push(Node* head, int x){
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = x;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}else{
newNode->next = head;
head = newNode;
}
return head;
}
int pop(Node** head){
if(head == NULL){
printf("the stack is already empyt, no element can be pop!\n");
return -1;
}
int result = (*head) -> value;
Node* temp = *head;
*head = (*head) -> next;
free(temp);
return result;
}
int top(Node* head){
int result;
if(head == NULL){
printf("the stack is empty!");
return -1;
}
result = head -> value;
return result;
}
void traverse(Node* head){
Node* temp = head;
while(temp != NULL){
printf("%ld ", temp->value);
temp = temp -> next;
}
printf("\n");
}