把一个单向链表反转过来,示例代码如下:
/*
reverse_link.c
Reverse a single linked list.
gcc reverse_link.c
./a.out
valgrind --tool=memcheck ./a.out
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* reverse(struct node* head)
{
if (NULL == head) return NULL;
struct node* previous = NULL;
struct node* next = NULL;
for (;;) {
next = head->next;
head->next = previous;
if (NULL == next) return head;
previous = head;
head = next;
}
}
struct node* new_node(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
//TODO if (NULL == node) ...
node->data = data;
node->next = NULL;
return node;
}
void append(struct node** head, int data)
{
if (NULL == *head) {
*head = new_node(data);
return;
}
struct node* next = *head;
for (; next->next; ) {
next = next->next;
}
next->next = new_node(data);
}
void print(struct node* head)
{
struct node* p = head;
for (; p; p = p->next) {
printf("%d\t", p->data);
}
printf("\n");
}
void delete(struct node* head)
{
struct node* next = head;
for (;; ) {
if (NULL == head) break;
next = head->next;
free(head);
head = next;
}
head = NULL;
}
int main()
{
struct node* head = NULL;
int data[] = {1, 3, 5, 7, 2, 4, 6, 8};
int i;
for (i = 0; i < sizeof(data) / sizeof(int); i++) {
append(&head, data[i]);
}
print(head);
head = reverse(head);
print(head);
delete(head);
return 0;
}
运行结果:
flying-bird@flyingbird:~/examples/cpp/reverse_link$ gcc reverse_link.c
flying-bird@flyingbird:~/examples/cpp/reverse_link$ ./a.out
1 3 5 7 2 4 6 8
8 6 4 2 7 5 3 1
flying-bird@flyingbird:~/examples/cpp/reverse_link$ valgrind --tool=memcheck ./a.out
==3087== Memcheck, a memory error detector
==3087== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3087== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3087== Command: ./a.out
==3087==
1 3 5 7 2 4 6 8
8 6 4 2 7 5 3 1
==3087==
==3087== HEAP SUMMARY:
==3087== in use at exit: 0 bytes in 0 blocks
==3087== total heap usage: 8 allocs, 8 frees, 64 bytes allocated
==3087==
==3087== All heap blocks were freed -- no leaks are possible
==3087==
==3087== For counts of detected and suppressed errors, rerun with: -v
==3087== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
flying-bird@flyingbird:~/examples/cpp/reverse_link$
附:valgrind介绍: http://blog.csdn.net/a_flying_bird/article/details/20395033