链表的介绍和使用

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

/**

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

}

}

};

相关推荐
牧瀬クリスだ21 分钟前
优先级队列——堆
java·开发语言·数据结构
香蕉鼠片26 分钟前
第三大的数
数据结构·算法·leetcode
汀、人工智能27 分钟前
[特殊字符] 第28课:相交链表
数据结构·算法·链表·数据库架构··相交链表
计算机安禾30 分钟前
【数据结构与算法】第32篇:交换排序(一):冒泡排序
c语言·数据结构·c++·算法·链表·排序算法·visual studio code
win水1 小时前
二十三,哈希表
数据结构·哈希算法·散列表
汀、人工智能9 小时前
[特殊字符] 第21课:最长有效括号
数据结构·算法·数据库架构·图论·bfs·最长有效括号
Boop_wu9 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
故事和你9110 小时前
洛谷-算法1-2-排序2
开发语言·数据结构·c++·算法·动态规划·图论
迈巴赫车主12 小时前
蓝桥杯3500阶乘求和java
java·开发语言·数据结构·职场和发展·蓝桥杯
高一要励志成为佬12 小时前
【数据结构】算法复杂度
数据结构