每日一题 春季 Day 01 (反转链表篇)
AcWing 35. 反转链表
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
链表操作 迭代版本
/**
* 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) {
if(!head||!head->next)return head; //先判断head是否为空 或者只有head一个 是的话直接返回head
//思路 让b指向a 然后往后跳一位 直到b为NULL 然后跳出
auto a=head,b=a->next;
while(b){
auto c=b->next;
b->next=a;
a=b,b=c;
}
head->next=NULL;//让head指向空
return a;
}
};
链表操作 递归版本
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head||!head->next)return head; //先判断head是否为空 或者只有head一个 是的话直接返回head
auto tail=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return tail;
}
};
leetcode 92 反转链表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) {
auto dummyNode = new ListNode(-1);//虚拟头节点
dummyNode->next=head;
auto a=dummyNode;
for(int i=0;i<left-1;i++)a=a->next;//让a走到left左边一额位置
auto b = a->next,c=b->next;
for(int i=0;i<right-left;i++){
auto d=c->next;
c->next=b;//让c指向b
b=c,c=d; //b和c分别往后跳一步
}
//结束之后 b会走到right点 c在之后一个点
// 下一步让a->next 指向c 让a指向b
a->next->next=c;
a->next=b;
return dummyNode->next;
}
};