链表的介绍和使用

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

/**

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

}

}

};

相关推荐
求学的小高5 分钟前
数据结构Day10(ASL、二分查找、分块查找)
数据结构·笔记·考研
算法鑫探26 分钟前
算法与数据结构 以及算法复杂度
c语言·数据结构·算法·新人首发
迷途之人不知返31 分钟前
List的学习
数据结构·c++·学习·list
6Hzlia32 分钟前
【Hot 100 刷题计划】 LeetCode 23. 合并 K 个升序链表 | C++ 顺序合并
c++·leetcode·链表
啊哦呃咦唔鱼1 小时前
Leetcodehot100-215. 数组中的第K个最大元素
数据结构·算法·leetcode
苏渡苇1 小时前
Redis 核心数据结构(二)——List 与消息队列
数据结构·redis·list·redis发布订阅
shehuiyuelaiyuehao1 小时前
算法12,滑动窗口,将x减到0的最小操作数
java·数据结构·算法
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 19. 删除链表的倒数第 N 个结点 | C++ 双指针单趟遍历
c++·leetcode·链表
li星野2 小时前
链表通关八题:从反转链表到两数相加,手撕LeetCode高频题
数据结构·学习·leetcode·链表
流年如夢2 小时前
顺序表 -->增、删、查、改等详细操作
c语言·数据结构