LeetCode OJ Reverse Linked List

题目
这里写图片描述

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

代码
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);
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页