365天挑战LeetCode1000题——Day 070 二叉树最大宽度 反转链表 重排链表 K 个一组翻转链表
662. 二叉树最大宽度
代码实现(看题解)
class Solution {
public:int widthOfBinaryTree(TreeNode* root) {unsigned long long res = 1;vector<pair<TreeNode *, unsigned long long>> arr;arr.emplace_back(root, 1L);while (!arr.empty()) {vector<pair<TreeNode *, unsigned long long>> tmp;for (auto &[node, index] : arr) {if (node->left) {tmp.emplace_back(node->left, index * 2);}if (node->right) {tmp.emplace_back(node->right, index * 2 + 1);}}res = max(res, arr.back().second - arr[0].second + 1);arr = move(tmp);}return res;}
};
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* prev = nullptr;ListNode* curr = head;while (curr) {ListNode* nex = curr->next;curr->next = prev;prev = curr;curr = nex;}return prev;}
};
143. 重排链表
代码实现(自解)
/*** 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:void reorderList(ListNode* head) {int k = 0;ListNode* tmp;while (tmp) {k++;tmp = tmp->next;}k /= 2;ListNode* newHead = head;while (k--) {ListNode* tail = newHead;while (tail->next && tail->next->next) {tail = tail->next;}ListNode* tailMinusOne = tail;tail = tail->next;tailMinusOne->next = nullptr;tail->next = newHead->next;newHead->next = tail;newHead = tail->next;}}
};
25. K 个一组翻转链表
代码实现(自解)
/*** 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 {
private:bool check(ListNode* node, vector<int>& tmp, int k) {int i = 0;int k1 = k;while (k1-- && node) {// cout << node->val;tmp[i++] = node->val;node = node->next;}return i == k;}
public:ListNode* reverseKGroup(ListNode* head, int k) {if (!head) return nullptr;vector<int> tmp(k);ListNode* n1 = head, *n2 = head;while (check(n1, tmp, k)) {// cout << 1 << endl;int k1 = k;while (k1--) {n2->val = tmp[k1];n2 = n2->next;}n1 = n2;}return head;}
};
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!