定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* h = head, *p, *pre;
if(!h || !h->next)
return head;
pre = head;
p = head->next;
while(p) {
ListNode* next = p->next;
p->next = pre;
pre = p;
p = next;
}
h->next = nullptr;
return pre;
}
};
虽然能写对,但不能一次性写对哎。
同类型题:
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(!head || !head->next || right-left < 1)
return head;
ListNode* h = head, *hpre = nullptr;
int i = 1;
while(i != left) {
hpre = h;
h = h->next;
i++;
}
ListNode* pre = h, *p = h->next;
while(i != right && p) {
ListNode* next = p->next;
p->next = pre;
pre = p;
p = next;
i++;
}
if(hpre)
hpre->next = pre;
h->next = p;
if (!hpre)
return pre;
else
return head;
}
};
悲伤,就是不能一次写对,得调试改哎。