24)反转链表
迭代法
class Solution{
public:
ListNode* reverseList(ListNode* head){
ListNode* pre = nullptr, *cur = head;
while(cur){
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
递归法
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;
}
};
25)链表中的两数相加
class Solution {
public:
ListNode* reverseList(ListNode* l){
if(!l || !l->next) return l;
ListNode* newhead = reverseList(l->next);
l->next->next = l;
l->next = nullptr;
return newhead;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode *pre = nullptr;
int carry = 0;
while(l1!=nullptr || l2!=nullptr){
int val = carry;
if(l1 != nullptr){
val += l1->val;
l1 = l1->next;
}
if(l2 != nullptr){
val += l2->val;
l2 = l2->next;
}
carry = val / 10;
val = val % 10;
pre = new ListNode(val, pre);
}
if(carry) pre = new ListNode(carry, pre);
return pre;
}
};
26)重排链表
(z字型连接)
class Solution{
public:
ListNode* reverseList(ListNode* l1){
if(!l1 || !l1->next) return l1;
ListNode* newl1 = reverseList(l1->next);
l1->next->next = l1;
l1->next = nullptr;
return newl1;
}
void reorderList(ListNode* head){
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* slow=dummy, *fast=dummy;
while(fast!=nullptr && fast->next!=nullptr){
slow = slow->next;
fast = fast->next->next;
}
ListNode* headB = slow->next;
slow->next = nullptr;
ListNode* p1 = head;
ListNode* p2 = reverseList(headB);
ListNode* p3 = nullptr;
while(p2!=nullptr){
p3 = p1->next;
p1->next = p2;
p1 = p2;
p2 = p3;
}
}
};