Skip to content

Commit 65d3937

Browse files
committed
add simple sort to Linked_List implementation
1 parent d635ee5 commit 65d3937

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

include/express/linklist.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ extern SC_EXPRESS_EXPORT void LISTinitialize PROTO( ( void ) );
129129
extern SC_EXPRESS_EXPORT void LISTcleanup PROTO( ( void ) );
130130
extern SC_EXPRESS_EXPORT Linked_List LISTcreate PROTO( ( void ) );
131131
extern SC_EXPRESS_EXPORT Linked_List LISTcopy PROTO( ( Linked_List ) );
132+
extern SC_EXPRESS_EXPORT void LISTsort PROTO( ( Linked_List, int (*comp)(void*, void*) ) );
133+
extern SC_EXPRESS_EXPORT void LISTswap PROTO( ( Link, Link ) );
132134
extern SC_EXPRESS_EXPORT Generic LISTadd_first PROTO( ( Linked_List, Generic ) );
133135
extern SC_EXPRESS_EXPORT Generic LISTadd_last PROTO( ( Linked_List, Generic ) );
134136
extern SC_EXPRESS_EXPORT Generic LISTadd_after PROTO( ( Linked_List, Link, Generic ) );

src/express/linklist.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,38 @@ void LISTfree( Linked_List list ) {
6767
LIST_destroy( list );
6868
}
6969

70+
void LISTsort( Linked_List list, int (*comp)(void*, void*)) {
71+
unsigned int moved;
72+
Link node, prev;
73+
74+
if (LISTempty(list))
75+
return;
76+
77+
while (true) {
78+
for ( node = list->mark->next, moved = 0; node != list->mark; node = node->next ) {
79+
prev = node->prev;
80+
if (prev != list->mark && comp(prev->data, node->data) < 0) {
81+
LISTswap(prev, node);
82+
moved++;
83+
}
84+
}
85+
if (moved == 0)
86+
break;
87+
}
88+
}
89+
90+
void LISTswap( Link p, Link q ) {
91+
Generic tmp;
92+
93+
if( p == LINK_NULL || q == LINK_NULL || p == q )
94+
return;
95+
96+
tmp = p->data;
97+
p->data = q->data;
98+
q->data = tmp;
99+
}
100+
101+
70102
Generic LISTadd_first( Linked_List list, Generic item ) {
71103
Link node;
72104

0 commit comments

Comments
 (0)