链表的介绍和使用

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

/**

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

}

}

};

相关推荐
想要成为糕糕手8 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
tyung11 小时前
Go 手写 Wait-Free SPSC 无界队列:无 CAS、无锁、泛型节点池
数据结构·后端·go
Chen_harmony11 小时前
一、数据结构概念和复杂度计算
数据结构
小欣加油11 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
fie888913 小时前
LBP + HOG 特征检测与识别 MATLAB 实现
数据结构·算法·matlab
退休倒计时14 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
AbandonForce15 小时前
滑动窗口:定长滑动窗口与不定长滑动窗口
数据结构·c++·算法
炸薯条!15 小时前
二叉树的链式表示(2)
java·数据结构·算法
YHHLAI16 小时前
JavaScript 数据结构精讲:数组底层与实战避坑
开发语言·javascript·数据结构
Coder-magician16 小时前
《代码随想录》刷题打卡day12:二叉树part02
数据结构·c++·算法