-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.c
106 lines (86 loc) · 2.1 KB
/
test.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* Prompts user to enter a set of random integers. When 'Q' is entered,
* display the integers in ascending order.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
typedef struct node {
int value;
struct node *next;
} node_t;
/**
* Initializes when head is NULL and assigns initial value
*
*/
void init(node_t **headp, int value) {
node_t *newp;
newp = malloc(sizeof(node_t));
newp->value = value;
newp->next = NULL;
if (*headp == NULL) {
*headp = newp;
}
}
/**
* Inserts a node into a sorted list
*/
void insert(node_t **headp, int value) {
node_t *currp;
node_t *prevp = NULL;
// Handle empty list by initializing it
if (*headp == NULL) {
init(headp, value);
return;
}
node_t *newp;
newp = malloc(sizeof(node_t));
newp->value = value;
newp->next = NULL;
// Find where it goes
for (currp = *headp; currp; currp = currp->next) {
if (currp->value >= value) {
if (prevp == NULL) { // insert at beginning of list
*headp = newp;
newp->next = currp;
break;
} else { // insert between two existing nodes
prevp->next = newp;
newp->next = currp;
break;
}
} else if (currp->next == NULL) { // append to end of list
currp->next = newp;
break;
}
prevp = currp;
}
}
int main(int argc, char **argv) {
node_t *headp = NULL;
node_t *currp;
char inbuf[80];
memset(inbuf, '\0', sizeof(inbuf));
int value = 0;
// Prompt for list of unsorted integers
while (*inbuf != 'Q') {
printf("Enter a number or 'Q' to quit: ");
// Get input from console
fgets(inbuf, sizeof(inbuf),stdin);
char *p = strchr(inbuf, '\n');
*p = '\0'; // Clear out the trailing newline
if (*inbuf == 'Q')
break;
if (sscanf(inbuf, "%d", &value) > 0)
// Process valid integer
insert(&headp, value);
else
// Ignore any input not an integer
printf("** ignored input\n");
}
// Done with input, now display the sorted list
for (currp = headp; currp; currp = currp->next) {
printf("%d\n", currp->value);
}
}