链表的介绍和使用

链表是数据结构中的一个重要组成部分,我们通过对链表的学习也可以提高对指针的理解。

/**

* 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* cur1=l1,* cur2=l2;

ListNode* newhead=new ListNode(0);//虚拟头节点

ListNode* prev=newhead;

int t=0;

while(cur1||cur2||t){

if(cur1){

t+=cur1->val;

cur1=cur1->next;

}

if(cur2){

t+=cur2->val;

cur2=cur2->next;

}

prev->next=new ListNode(t%10);

prev=prev->next;

t/=10;

}

prev=newhead->next;

delete newhead;

return prev;

}

};

/**

* 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* swapPairs(ListNode* head) {

if(head==nullptr||head->next==nullptr) return head;

ListNode* newhead= new ListNode(0);

newhead->next=head;

ListNode*prev=newhead,*cur=prev->next,*next=cur->next,*nnext=next->next;

while(cur&&next){

prev->next=next;

next->next=cur;

cur->next=nnext;

prev=cur;

cur=nnext;

if(cur) next=cur->next;

if(next) nnext=next->next;

}

cur=newhead->next;

delete newhead;

return cur;

}

};

/**

* 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) {

if (head == nullptr || head->next == nullptr || head->next->next == nullptr)

return;

// 1. 找到中间节点

ListNode* slow = head;

ListNode* fast = head;

while (fast->next && fast->next->next) {

slow = slow->next;

fast = fast->next->next;

}

// 2. 反转后半部分链表

ListNode* head2 = nullptr;

ListNode* cur = slow->next;

slow->next = nullptr;

while (cur) {

ListNode* next = cur->next;

cur->next = head2;

head2 = cur;

cur = next;

}

// 3. 合并两个链表

ListNode* cur1 = head;

ListNode* cur2 = head2;

while (cur1 && cur2) {

ListNode* next1 = cur1->next;

ListNode* next2 = cur2->next;

cur1->next = cur2;

cur2->next = next1;

cur1 = next1;

cur2 = next2;

}

}

};

相关推荐
Zhang~Ling14 小时前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
smj2302_7968265217 小时前
解决leetcode第3934题最短唯一子数组
数据结构·python·算法·leetcode
iiiiyu17 小时前
面向对象和集合编程题
java·开发语言·前端·数据结构·算法·编程语言
变量未定义~17 小时前
最长回文子串
数据结构·算法
代码中介商17 小时前
AVL树:自平衡二叉搜索树的奥秘
数据结构
玛卡巴卡ldf18 小时前
【LeetCode 手撕算法】(多维动态规划)不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离
java·数据结构·算法·leetcode·动态规划·力扣
被AI抢饭碗的人18 小时前
算法:数据结构
数据结构·算法
淞綰19 小时前
c语言的练习-字符串的练习-寻找最长连续字符以及出现次数
c语言·数据结构·学习·算法·c语言的练习
qq_2965532720 小时前
[特殊字符] 搜索插入位置:从O(n)到O(log n)的优雅进化
数据结构·算法·面试·分类·柔性数组
凯瑟琳.奥古斯特20 小时前
力扣3654:二维矩阵连续空位统计
数据结构·数据库·算法·职场和发展