链表是一种数据结构,其中每个元素都可以指向下一个元素,根据这一特性,我们可以从头指针依次遍历整个链表,链表遍历慢,但删改快
nullptr在c++中充当空指针,而NULL充当0
三目运算符格式
int a,b,c;
c = a > b ? a : b;//问号前为真则返回冒号前,否则返回冒号后的
下面是三道力扣上的链表题
两数相加
https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-interview-150
/**
* 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* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while(l1 || l2)
{
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if(!head)
{
head = tail = new ListNode(sum % 10);
}
else
{
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if(l1)
{
l1 = l1->next;
}
if(l2)
{
l2 = l2->next;
}
}
if(carry)
{
tail->next = new ListNode(carry);
}
return head;
}
};
合并两个有序链表
https://leetcode.cn/problems/merge-two-sorted-lists/description/?envType=study-plan-v2&envId=top-interview-150
/**
* 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* list1, ListNode* list2) {
ListNode *head = nullptr,*tail = nullptr;
if(!list1)
{
return list2;
}
if(!list2)
{
return list1;
}
while(list1 && list2)
{
int n1 = list1 ? list1->val : 200;
int n2 = list2 ? list2->val : 200;
int temp;
if(n1 < n2)
{
list1 = list1->next;
temp = n1;
}
else
{
list2 = list2->next;
temp = n2;
}
if(!head)
{
head = tail = new ListNode(temp);
}
else
{
tail->next = new ListNode(temp);
tail = tail->next;
}
}
if(list1)
{
tail->next = list1;
}
else
{
tail->next = list2;
}
return head;
}
};
随机链表的复制
https://leetcode.cn/problems/copy-list-with-random-pointer/description/?envType=study-plan-v2&envId=top-interview-150
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head)
{
return head;
}
Node *nhead = nullptr,*tail = nullptr,*temp = head;
unordered_map <Node*,Node*> map;
temp = head;
nhead = tail = new Node(temp->val);
map[head] = tail;
temp = temp->next;
while(temp)
{
tail->next = new Node(temp->val);
map[temp] = tail->next;
tail = tail->next;
temp = temp->next;
}
temp = head;
while(temp)
{
if(temp->random)
{
map[temp]->random = map[temp->random];
}
temp = temp->next;
}
return nhead;
}
};