Leetcode每日一题:206.reverse-linked-list/solution(反转链表)_递归
思路:这题还是比较容易的,递归和迭代复杂度仅为O(n);
Leetcode每日一题:206.reverse-linked-list/solution(反转链表)_递归_02

// 递归版
struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode *hh = NULL;
ListNode *reverseList(ListNode *head)
{
	if (head == NULL || head->next==NULL)
	{
		return head;
	}
	fun(head, head->next);
	return hh;
}

void fun(ListNode *p, ListNode *q)
{
	if (q->next == NULL)
	{
		q->next = p;
		p->next=NULL;
		hh = q;
		return;
	}
	else
	{
		fun(q, q->next);
		q->next = p;
		p->next = NULL;
	}
}

//迭代版
ListNode *reverseList(ListNode *head) {
    ListNode *prev = NULL;
    ListNode *curr = head;
    while (curr != NULL) {
        ListNode *nextTemp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}