码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ Reverse Linked List

时间:2015-05-05 10:40:13      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:递归   链表   struct   reverse   

题目
技术分享

思路
翻转单向链表,这里题目要求用递归和非递归实现,具体思路见代码。

代码
a)非递归

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode * Before = NULL;
    struct ListNode * OriPresent = head;
    while (OriPresent != NULL) {
        struct ListNode * Present = (struct ListNode*)malloc(sizeof(struct ListNode));
        Present->val = OriPresent->val;
        Present->next = Before;
        Before = Present;
        OriPresent = OriPresent->next;
    }
    return Before;
}

b)递归

struct ListNode * reverse(struct ListNode * Before, struct ListNode * OriPresent) {
    if (OriPresent == NULL) return Before;
    struct ListNode * Present = (struct ListNode*)malloc(sizeof(struct ListNode));
    Present->next = Before;
    Present->val = OriPresent->val;
    return reverse(Present, OriPresent->next);
}

struct ListNode* reverseList(struct ListNode* head) {
    return reverse(NULL, head);
}

LeetCode OJ Reverse Linked List

标签:递归   链表   struct   reverse   

原文地址:http://blog.csdn.net/u012925008/article/details/45498545

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!