单链表倒序:
#include
<
stdio.h
>
struct link
{
int value;
struct link * next;
} ;
void output_link( struct link * head)
{
printf( " " );
while (head != NULL)
{
printf( " [%d] " , head -> value);
head = head -> next;
}
}
void rever_output_link( struct link * head)
{
if (head) {
rever_output_link(head -> next);
printf( " [%d] " ,head -> value);
}
}
struct link * create_link ( int n)
{
struct link * head = malloc( sizeof ( struct link));
struct link * tmp, * pre;
int i;
pre = head;
head -> value = rand();
for ( i = 0 ; i < n - 1 ; i ++ )
{
tmp = malloc( sizeof ( struct link));
tmp -> value = rand();
tmp -> next = NULL;
pre -> next = tmp;
pre = pre -> next ;
}
return head;
}
struct link * revert_link( struct link * head)
{
struct link * left, * mid , * tmp;
left = head ;
mid = head -> next;
left -> next = NULL;
while (mid != NULL)
{
tmp = mid -> next ;
mid -> next = left;
left = mid;
mid = tmp;
}
return left;
}
void del_link( struct link * head)
{
struct link * tmp;
while (head != NULL)
{
tmp = head;
head = head -> next;
free(tmp);
}
}
int main()
{
struct link * head = create_link( 6 );
struct link * tmp ;
output_link(head);
tmp = revert_link(head);
output_link(tmp);
del_link(head);
return 0 ;
}
struct link
{
int value;
struct link * next;
} ;
void output_link( struct link * head)
{
printf( " " );
while (head != NULL)
{
printf( " [%d] " , head -> value);
head = head -> next;
}
}
void rever_output_link( struct link * head)
{
if (head) {
rever_output_link(head -> next);
printf( " [%d] " ,head -> value);
}
}
struct link * create_link ( int n)
{
struct link * head = malloc( sizeof ( struct link));
struct link * tmp, * pre;
int i;
pre = head;
head -> value = rand();
for ( i = 0 ; i < n - 1 ; i ++ )
{
tmp = malloc( sizeof ( struct link));
tmp -> value = rand();
tmp -> next = NULL;
pre -> next = tmp;
pre = pre -> next ;
}
return head;
}
struct link * revert_link( struct link * head)
{
struct link * left, * mid , * tmp;
left = head ;
mid = head -> next;
left -> next = NULL;
while (mid != NULL)
{
tmp = mid -> next ;
mid -> next = left;
left = mid;
mid = tmp;
}
return left;
}
void del_link( struct link * head)
{
struct link * tmp;
while (head != NULL)
{
tmp = head;
head = head -> next;
free(tmp);
}
}
int main()
{
struct link * head = create_link( 6 );
struct link * tmp ;
output_link(head);
tmp = revert_link(head);
output_link(tmp);
del_link(head);
return 0 ;
}