-
Notifications
You must be signed in to change notification settings - Fork 4
/
lec17_a.c
74 lines (64 loc) · 1.02 KB
/
lec17_a.c
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
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node *next;
};
struct Node *head;
struct Node *pop()
{
struct Node *new_head = head;
head = head->next;
return new_head;
}
void push(char c)
{
struct Node *insert = (struct Node *)malloc(sizeof(struct Node));
insert->data = c;
insert->next = head;
head = insert;
}
void reverse(char C[], int n)
{
// build the stack
for (int i = 0; i < n; i++)
{
push(C[i]);
}
for (int i = 0; i < n; i++)
{
struct Node *popped = pop();
C[i] = popped->data;
}
}
void reverse_efficient(char C[], int n)
{
int i = 0;
int j = n - 1;
while (i < j)
{
char t = C[j];
C[j] = C[i];
C[i] = t;
i++;
j--;
}
}
void print_array(char C[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%c ", C[i]);
}
printf("\n");
}
int main(void)
{
head = NULL;
char C[] = {'s', 'h', 'e', 'h', 'r', 'y', 'a', 'r'};
print_array(C, 8);
reverse_efficient(C, sizeof(C) / sizeof(C[0]));
print_array(C, 8);
return 0;
}