A Za, A Za, Fighting...

坚信:勤能补拙

反转链表 循环与递归

题目来源:
http://zhedahht.blog.163.com/blog/static/2541117420073471124487/

#include<stdio.h>
#include
<stdlib.h>
#include
<string.h>

struct Node {
    
char value;
    
struct Node *next;
};

struct Node *
list_reverse(
struct Node *head)
{
    
struct Node *tmp, *cur, *pre = NULL;
    cur 
= head;
    
while(cur) {
        tmp 
= cur->next;
        cur
->next = pre;
        pre 
= cur;
        cur 
= tmp;
    }
    
return pre;
}

struct Node *
list_reverse_recursive(
struct Node *head)
{
    
struct Node *rv;
    
if(head && head->next) {
        rv 
= list_reverse_recursive(head->next);
        head
->next->next = head;
        head
->next = NULL;
        
return rv;
    } 
else 
        
return head;
}

void
test_print(
struct Node *head)
{
    
while(head) {
        printf(
"%c\t", head->value);
        head 
= head->next;
    }
    printf(
"\n");
}

int
main(
int argc, char **argv)
{
    
struct Node d = {'d', NULL};
    
struct Node c = {'c'&d};
    
struct Node b = {'b'&c};
    
struct Node a = {'a'&b};

    test_print(
&a);

    
struct Node *rev_first = list_reverse(&a);

    test_print(rev_first);

    
struct Node *rev_second = list_reverse_recursive(rev_first);

    test_print(rev_second);

    
return 0;
}


posted on 2011-06-12 16:15 simplyzhao 阅读(219) 评论(0)  编辑 收藏 引用 所属分类: M_面试题集锦


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2011年6月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜