反转一个单向链表

把一个单向链表反转过来,示例代码如下:

/*
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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值