题目
思路
翻转单向链表,这里题目要求用递归和非递归实现,具体思路见代码。
代码
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
原文地址:http://blog.csdn.net/u012925008/article/details/45498545