Кольцевой список
Добавлено: 07 май 2013, 19:43
Код: Выделить всё
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct NODE {
int value;
struct NODE * next;
} node_t;
void push(node_t ** pRing, int nValue) {
node_t * pNode = malloc(sizeof(node_t));
assert ( pNode );
pNode->value = nValue;
if ( ! *pRing ) {
pNode->next = pNode;
*pRing = pNode;
}
else {
pNode->next = (*pRing)->next;
(*pRing)->next = pNode;
*pRing = pNode;
}
}
void rotate(node_t ** pRing, int steps) {
assert ( *pRing && steps > 0 );
while ( steps-- )
*pRing = (*pRing)->next;
}
int top(const node_t * ring) {
return ring->value;
}
int is_empty(const node_t * ring) {
return ( ! ring );
}
int shift(node_t ** pRing) {
int ret;
assert ( *pRing );
ret = (*pRing)->value;
if ( (*pRing)->next == *pRing ) {
free(*pRing);
*pRing = NULL;
}
else {
node_t * pPrev = (*pRing)->next;
while ( pPrev->next != *pRing )
pPrev = pPrev->next;
pPrev->next = (*pRing)->next;
free(*pRing);
*pRing = pPrev->next;
}
return ret;
}
node_t * find(const node_t * ring, const int value) {
const node_t * current = ring;
do {
if ( current->value == value )
return (node_t*)current;
current = current->next;
} while ( current != ring );
return NULL;
}
int main(void) {
node_t * ring = NULL;
int count, i, value;
printf("Number of elements: ");
assert ( scanf("%d", &count) == 1 && count > 0 );
for ( i = 0; i < count; ++i ) {
printf("Value #%d: ", i + 1);
assert( scanf("%d", &value) == 1 );
push(&ring, value);
}
rotate(&ring, 1);
while ( ! is_empty(ring) )
printf("%d ", shift(&ring));
return 0;
}
цикл должен найти N-й элемент, удалить его, начать с (N+1)-ого опять найти N-й, удалить и т.д. пока не останется 1 элемент, затем вывести его на экран.
Буду очень благодарен за помощь