苏州网站建设哪家更好,四川省建设工程信息网官网二建注册,好创意设计大赛官网,企业网站备案管理系统1. 题目
定义一个函数#xff0c;输入一个链表的头节点#xff0c;反转该链表并输出反转后链表的头节点。
示例:
输入: 1-2-3-4-5-NULL
输出: 5-4-3-2-1-NULL限制#xff1a;
0 节点个数 5000来源#xff1a;力扣输入一个链表的头节点反转该链表并输出反转后链表的头节点。
示例:
输入: 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 *newHead reverseList(head-next);head-next-next head;//head-next下一个的next指向前面headhead-next NULL;//避免循环链表return newHead;//每层都返回最后一个节点新的头}
};