题单:LeetCode链表
2. 两数相加
/**
* 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) {
auto dummy = new ListNode(-1), cur = dummy;
int t = 0;
while(l1 || l2 || t)
{
if(l1) t += l1->val, l1 = l1->next;
if(l2) t += l2->val, l2 = l2->next;
cur = cur->next = new ListNode(t % 10);
t /= 10;
}
return dummy->next;
}
};
作者:NFYD
链接:https://www.acwing.com/activity/content/code/content/1437840/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
19. 删除链表的倒数第 N 个结点
/**
* 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* removeNthFromEnd(ListNode* head, int k) {
//建立一个虚拟头结点,因为头结点可能会被删掉,这样便于操作
auto dummy = new ListNode(-1);
dummy->next = head;
int len = 0; //计算链表长度
for(auto p = dummy; p; p = p->next) len ++ ;
auto p = dummy;
//跳到要删除节点的前一个点,然后p->next = p->next->next;
for(int i = 0; i < len - k - 1; i ++ ) p = p->next;
p->next = p->next->next;
return dummy->next;
}
};
作者:NFYD
链接:https://www.acwing.com/activity/content/code/content/3860044/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
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) {
auto dummy = new ListNode(-1), tail = dummy;
while(l1 && l2)
{
if(l1->val < l2->val)
{
tail = tail->next = l1;
l1 = l1->next;
}
else
{
tail = tail->next = l2;
l2 = l2->next;
}
}
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return dummy->next;
}
};
23. 合并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 {
public:
struct Cmp
{
bool operator() (ListNode* a, ListNode* b)
{
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, Cmp> heap;
auto dummy = new ListNode(-1);
auto tail = dummy;
for(auto l : lists) if(l) heap.push(l);
while(heap.size())
{
auto t = heap.top();
heap.pop();
tail = tail->next = t;
if(t->next) heap.push(t->next);
}
return dummy->next;
}
};
原创文章,作者:端木书台,如若转载,请注明出处:https://blog.ytso.com/277928.html