前言
date: 9.21
中秋假節
彙總: 每日一題系列_算法提升
合并兩個有序連結清單
題目: leetcode 21.合并兩個有序連結清單
遞歸版本:
/**
* 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* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr)
return l2;
if (l2 == nullptr)
return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
非遞歸版本:
/**
* 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* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr)
return l2;
if (l2 == nullptr)
return l1;
ListNode* head = new ListNode();
ListNode* p1 = l1, *p2 = l2, *p = head;
while (p1 != nullptr && p2 != nullptr) {
if (p1->val < p2->val) {
p->next = p1;
p1 = p1->next;
p = p->next;
} else {
p->next = p2;
p2 = p2->next;
p = p->next;
}
}
while(p1 != nullptr) {
p->next = p1;
p1 = p1->next;
p = p->next;
}
while(p2 != nullptr) {
p->next = p2;
p2 = p2->next;
p = p->next;
}
p = head->next;
delete head;
return p;
}
};
反轉連結清單
題目: leetcode 206.反轉連結清單
開多幾個輔助指針就好啦
/**
* 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* reverseList(ListNode* head) {
ListNode* pre = nullptr, *cur = head, *next;
while(cur) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
回文連結清單
題目來源: leetcode 234回文連結清單
用個vec存一下吧。
/**
* 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:
bool isPalindrome(ListNode* head) {
vector<int> vec;
ListNode* p = head;
while(p) {
vec.push_back(p->val);
p = p->next;
}
int n = vec.size();
for (int i = 0; i < n / 2; i++)
if (vec[i] != vec[n - i - 1])
return false;
return true;
}
};