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) {
ListNode* tp = new ListNode(0);
ListNode* ans = tp;
while(l1 || l2){
if(!l2 || (l1 && l1->val < l2->val)){
tp->next = l1;
l1 = l1->next;
}else {
tp->next = l2;
l2 = l2->next;
}
tp=tp->next;
}
return ans->next;
}
};
206. 反转链表
递归写法
/**
* 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 == NULL || head->next == NULL) {
return head;
}
ListNode* cur = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return cur;
}
};
迭代写法
/**
* 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 == nullptr)return head;
ListNode* h1 = head,*ans = new ListNode(0);
ans=NULL;
while(head){
h1=head->next;
head->next = ans;
ans=head;
head=h1;
}
return ans;
}
};
剑指 Offer 36. 二叉搜索树与双向链表
中序遍历+链表构建。
链表问题感觉都是纸老虎,很吓人,但真正写过后,发现也就是普通的数组、dfs遍历+一些操作即可
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node* head,* lst;
void dfs(Node* x){
if(x->left)dfs(x->left);
if(!lst){
head=x;
lst = x;
}
else{
x->left=lst;
lst->right=x;
lst=x;
}
if(x->right)dfs(x->right);
}
Node* treeToDoublyList(Node* root) {
if(!root)return root;
dfs(root);
lst->right=head;
head->left=lst;
return head;
}
};