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



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