Форум » C/C++ для начинающих (C/C++ for beginners) » ­Рекурсивная функция удаления элемента односвязного списка по индексу с конца списка » Ответить

­Рекурсивная функция удаления элемента односвязного списка по индексу с конца списка

Сыроежка: [pre]#include <stdio.h> #include <stdlib.h> typedef struct TNode { int value; struct TNode *next; } TNode; void append( TNode **head, const int a[], size_t n ) { while ( *head ) head = &( *head )->next; for ( size_t i = 0; i < n; i++ ) { *head = malloc( sizeof( TNode ) ); if ( *head ) { ( *head )->value = a; ( *head )->next = NULL; head = &( *head )->next; } } } void display( TNode **head ) { for ( TNode *current = *head; current; current = current->next ) { printf( "%d ", current->value ); } } int remove_n( TNode **head, size_t n ) { static size_t pos; int success = 0; if ( *head ) { success = remove_n( &( *head )->next, n ); if ( ( success = ( !success && pos == n ) ) ) { TNode *tmp = *head; *head = ( *head )->next; free( tmp ); } else { ++pos; } } else { pos = 0; } return success; } int main( void ) { TNode *head = NULL; int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; const size_t N = sizeof( a ) / sizeof( *a ); append( &head, a, N ); display( &head ); putchar( '\n' ); remove_n( &head, 0 ); display( &head ); putchar( '\n' ); remove_n( &head, 1 ); display( &head ); putchar( '\n' ); remove_n( &head, 7 ); display( &head ); putchar( '\n' ); remove_n( &head, 7 ); display( &head ); putchar( '\n' ); remove_n( &head, 5 ); display( &head ); putchar( '\n' ); while ( head ) { remove_n( &head, 0 ); display( &head ); putchar( '\n' ); } }[/pre]­

Ответов - 0



полная версия страницы