剑指Offer - 面试题24. 反转链表

1. 题目

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
 
限制:
0 <= 节点个数 <= 5000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

相同题目:LeetCode 206. 反转链表

2.1 循环

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    	if(!head)
    		return head;
        ListNode *prev = NULL, *nt = head->next;
        while(head && head->next)
        {
        	head->next = prev;
        	prev = head;
        	head = nt;
        	nt = nt->next;
        }
        head->next = prev;
        return head;
    }
};

在这里插入图片描述

2.2 递归

class Solution {
    ListNode *newhead;
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode *nt = reverseList(head->next);
        head->next->next = head;//head->next下一个的next指向前面head
        head->next = NULL;//避免循环链表
        return nt;//每层都返回最后一个节点nt,新的头
    }
};
发布了626 篇原创文章 · 获赞 491 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/104301888
今日推荐