链表核心算法实战
链表操作是数据结构面试中的高频考点,涉及指针变换、内存管理及递归思维。以下整理五道经典题目,涵盖模拟、堆结构、分治等策略,代码均基于 C++ 实现。
1. 两数相加
两个链表逆序存储数字,个位对齐。直接遍历相加即可,关键在于处理进位。若最高位仍有进位,需新增节点。
/**
* 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* dummyHead = new ListNode(0);
ListNode* tail = dummyHead;
int carry = 0;
while (cur1 || cur2 || carry) {
if (cur1) {
carry += cur1->val;
cur1 = cur1->next;
}
if (cur2) {
carry += cur2->val;
cur2 = cur2->next;
}
ListNode* node = new ListNode(carry % 10);
tail->next = node;
tail = tail->next;
carry /= 10;
}
ListNode* result = dummyHead->next;
delete dummyHead;
return result;
}
};
2. 两两交换链表中的节点
通过调整指针指向完成节点交换。使用虚拟头结点简化边界处理,注意保存 next 指针防止断链。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode* dummyHead = (, head);
ListNode* prev = dummyHead;
ListNode* cur = head;
(cur && cur->next) {
ListNode* nextNode = cur->next;
ListNode* nNext = nextNode->next;
prev->next = nextNode;
cur->next = nNext;
nextNode->next = cur;
prev = cur;
cur = nNext;
}
ListNode* result = dummyHead->next;
dummyHead;
result;
}
};

