-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlists.c
139 lines (122 loc) · 2.45 KB
/
lists.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/* $Id: lists.c,v 1.1 2001/12/19 22:29:30 acs Exp $
Written by Adam Siepel, Spring 2001
Copyright 2001, Adam Siepel */
/* Simple list-handling functions, allowing indexing or either FIFO or
LIFO behavior. */
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "lists.h"
void
push ( List * q, void *v )
{
int i;
if ( q->ridx >= q->CAPACITY )
{
if ( q->lidx > 0 )
{
for ( i = q->lidx; i < q->ridx; i++ )
q->array[i - q->lidx] = q->array[i];
q->ridx -= q->lidx;
q->lidx = 0;
}
else
{
fprintf ( stderr, "ERROR: Exceeded list capacity\n" );
assert ( 0 );
}
}
q->array[q->ridx++] = v;
}
int
list_size ( List * l )
{
return ( l->ridx - l->lidx );
}
void *
list_get ( List * l, int i )
{
if ( i >= list_size ( l ) )
return NULL;
return ( l->array[l->lidx + i] );
}
void *
pop_queue ( List * q )
{
if ( q->lidx >= q->ridx )
return NULL;
return q->array[q->lidx++];
}
void *
peek_queue ( List * q )
{
if ( q->lidx >= q->ridx )
return NULL;
return q->array[q->lidx];
}
void *
pop_stack ( List * q )
{
if ( q->ridx <= q->lidx )
return NULL;
return q->array[--q->ridx];
}
void *
peek_stack ( List * s )
{
if ( s->ridx <= s->lidx )
return NULL;
return s->array[s->ridx - 1];
}
int
empty ( List * q )
{
return ( q->lidx >= q->ridx );
}
/* Must be executed on a new list before it is usable!!! */
void
init_list ( List * q, int nelements, int elementsz )
{
q->ridx = q->lidx = 0;
q->CAPACITY = nelements;
q->elementsz = elementsz;
q->array = ( void ** ) malloc ( nelements * elementsz );
}
void
copy_list ( List * new, List * old )
{
int i;
init_list ( new, old->CAPACITY, old->elementsz );
for ( i = 0; i < list_size ( old ); i++ )
push ( new, list_get ( old, i ) );
}
void
free_list ( List * q )
{
free ( q->array );
}
void
clear_list ( List * l )
{
l->ridx = l->lidx = 0;
}
void
list_delete ( List * l, int idx )
{
int i;
if ( idx >= list_size ( l ) )
return;
for ( i = idx + 1; i < list_size ( l ); i++ )
l->array[l->lidx + i - 1] = l->array[l->lidx + i];
l->ridx--;
}
/* note: pointer-based */
int
list_contains ( List * l, void *ptr )
{
int i;
for ( i = 0; i < list_size ( l ); i++ )
if ( list_get ( l, i ) == ptr )
return 1;
return 0;
}