1.反正链表
反转一个单链表。
递归解法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next)
return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
迭代解法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur)
{
ListNode* nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
return pre;
}
};
2.反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回反转后的链表 。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* pre=dummy;
int i=1;
for(;i<m;++i)
pre=pre->next; //找到反转的起始位置
head=pre->next;
for(;i<n;++i)
{
ListNode* nex=head->next;
head->next=nex->next;
nex->next=pre->next; //nex->next=head错,因为head(当前节点)位置会变
pre->next=nex; //当前节点的下一个节点调整为前驱节点的下一个节点
}
return dummy->next;
}
};