-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
114 lines (96 loc) · 2.43 KB
/
list.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
107
108
109
110
111
112
113
#include "list.h"
/*** Create a circular linked list which stores a set number of data nodes,
* and allocates memory for each node. This means that all memory in the
* list is still array accessible, and is thus easier to free up.
* Returns a pointer to the list.***/
listptr initlist(int N)
{
/*** Allocate memory for a single list construct ***/
listptr list = calloc(1, (sizeof *list));
/*** Allocate memory for an list of N nodes for the list***/
nodeptr array = calloc((N+1), (sizeof *array));
int i;
for(i=0;i<=N;++i)
{
array[i].next = &array[i+1];
}
array[N].next = list -> lastcmd = list -> arrayhead = \
list -> oldestcmd = &array[0];
array[N+1].next = NULL;
return list;
}
/*** Add a string to the list, increment its history number ***/
void addstring(char * laststring, listptr list)
{
static int count = 0;
++count;
if (count > HISTORYSIZE || count <= 1)
list -> oldestcmd = list -> oldestcmd -> next;
list -> lastcmd = list -> lastcmd -> next;
list -> lastcmd -> histnumber = count;
strncpy(list -> lastcmd -> string, laststring, MAXLINESIZE);
}
/*** Print all the strings in the list ***/
void printstrings(listptr list)
{
nodeptr printptr = list -> oldestcmd;
if(printptr)
{
while((strncmp(printptr -> string,"\0",1)) &&
(printptr != list -> lastcmd))
{
printptr = printptr -> next;
printf("%d %s\n", printptr -> histnumber,
printptr -> string);
}
}
}
/*** Print one string from the list, based on its history number ***/
void printcmd(int n, listptr list)
{
nodeptr printptr = list -> oldestcmd;
if(printptr)
{
while((strncmp(printptr -> string,"\0",1)) &&
(printptr != list -> lastcmd))
{
printptr = printptr -> next;
if (printptr -> histnumber == n)
{
printf("%d %s", printptr -> histnumber,
printptr -> string);
break;
}
}
}
}
/*** Execute one string from the list, based on its history number ***/
char * getcmd(int n, listptr list)
{
nodeptr printptr = list -> oldestcmd;
int wehaveacommand = 0;
if(printptr)
{
do
{
if (printptr -> histnumber == n)
{
wehaveacommand = 1;
break;
}
printptr = printptr -> next;
}
while((strncmp(printptr -> string,"\0",1)) &&
(printptr != list -> lastcmd -> next));
}
if(wehaveacommand)
return(printptr -> string);
else
return NULL;
}
/*** Free up all memory used by the list ***/
void destructlist(listptr * list)
{
free((*(list)) -> arrayhead);
free((*list));
}