链表的介绍和使用

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

/**

* 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;

}

}

};

相关推荐
小王不爱笑1323 小时前
排序算法 Java
数据结构·算法·排序算法
不想看见4043 小时前
Power of Four二进制特性--力扣101算法题解笔记
数据结构·算法
y = xⁿ3 小时前
【LeetCodehot100】T23:合并k个升序链表
java·数据结构·链表
_饭团4 小时前
指针核心知识:5篇系统梳理3
c语言·数据结构·算法·leetcode·面试·学习方法·改行学it
星空露珠4 小时前
又双叒叕统计被炸死的lua脚本
开发语言·数据结构·算法·游戏·lua
Via_Neo5 小时前
日期问题和日期常用API
数据结构·算法
小年糕是糕手6 小时前
【C++】string类(三)
开发语言·数据结构·c++·程序人生·算法
IronMurphy7 小时前
【算法二十五】105. 从前序与中序遍历序列构造二叉树 236. 二叉树的最近公共祖先
java·数据结构·算法
像污秽一样7 小时前
算法设计与分析-习题8.2
数据结构·算法·排序算法·dfs·化简