Leetcode每日一题:206.reverse-linked-list/solution(反转链表)

在这里插入图片描述
思路:这题还是比较容易的,递归和迭代复杂度仅为O(n);
在这里插入图片描述

// 递归版
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;
}

猜你喜欢

转载自blog.csdn.net/wyll19980812/article/details/109004168
今日推荐