别着急。 :)
正如你所说,你需要交换节点本身而不是只交换它们的值,然后你就在这里。 :)
#include <stdio.h>
#include <stdlib.h>
struct list
{
int value;
struct list *next;
};
void push_front( struct list **head, int value )
{
struct list *tmp = malloc( sizeof( struct list ) );
if ( tmp )
{
tmp->value = value;
tmp->next = *head;
*head = tmp;
}
}
void display( struct list *head )
{
for ( struct list *tmp = head; tmp; tmp = tmp->next )
{
printf( "%d ", tmp->value );
}
printf( "\n" );
}
void swap( struct list **head, int value )
{
while ( *head && ( *head )->value != value )
{
head = &( *head )->next;
}
if ( *head && ( *head )->next )
{
struct list *next = ( *head )->next->next;
( *head )->next->next = *head;
*head = ( *head )->next;
( *head )->next->next = next;
}
}
int main( void )
{
struct list *head = NULL;
push_front( &head, 4 );
push_front( &head, -5 );
push_front( &head, 3 );
push_front( &head, 7 );
push_front( &head, -1 );
push_front( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
swap( &head, 2 );
display( head );
return 0;
}
程序输出是
2 -1 7 3 -5 4
-1 2 7 3 -5 4
-1 7 2 3 -5 4
-1 7 3 2 -5 4
-1 7 3 -5 2 4
-1 7 3 -5 4 2
-1 7 3 -5 4 2
或者更有趣的例子
#include <stdio.h>
#include <stdlib.h>
struct list
{
int value;
struct list *next;
};
void push_front( struct list **head, int value )
{
struct list *tmp = malloc( sizeof( struct list ) );
if ( tmp )
{
tmp->value = value;
tmp->next = *head;
*head = tmp;
}
}
void display( struct list *head )
{
for ( struct list *tmp = head; tmp; tmp = tmp->next )
{
printf( "%d ", tmp->value );
}
printf( "\n" );
}
void swap( struct list **head, int value )
{
while ( *head && ( *head )->value != value )
{
head = &( *head )->next;
}
if ( *head && ( *head )->next )
{
struct list *next = ( *head )->next->next;
( *head )->next->next = *head;
*head = ( *head )->next;
( *head )->next->next = next;
}
}
int main( void )
{
struct list *head = NULL;
int a[] = { 2, -1, 7, 3, -5, 4 };
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
push_front( &head, a[i] );
display( head );
for ( size_t j = 0; j < i; j++ )
{
swap( &head, a[i] );
display( head );
}
printf( "\n" );
}
display( head );
return 0;
}
程序输出是
2
-1 2
2 -1
7 2 -1
2 7 -1
2 -1 7
3 2 -1 7
2 3 -1 7
2 -1 3 7
2 -1 7 3
-5 2 -1 7 3
2 -5 -1 7 3
2 -1 -5 7 3
2 -1 7 -5 3
2 -1 7 3 -5
4 2 -1 7 3 -5
2 4 -1 7 3 -5
2 -1 4 7 3 -5
2 -1 7 4 3 -5
2 -1 7 3 4 -5
2 -1 7 3 -5 4
2 -1 7 3 -5 4
像往常一样,我的答案是最好的。:)