LeetCode OJ Reverse Linked List

来源:互联网 发布:风险评价矩阵 编辑:程序博客网 时间:2024/06/18 12:31

题目
这里写图片描述

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

代码
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);}
0 0