目录
1.合并两个有序链表
21. 合并两个有序链表 - 力扣(LeetCode)
https://leetcode.cn/problems/merge-two-sorted-lists/
cpp
/**
* 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* mergeTwoLists(ListNode* list1, ListNode* list2) {
// 1. 处理特殊情况
if(!list1)
return list2;
if(!list2)
return list1;
// 2. 给两个链表分别创建两个新的指针
ListNode* ptr1 = list1;
ListNode* ptr2 = list2;
// 3. 创建一个新链表
ListNode* new_list = new ListNode(-1);
ListNode* tail = new_list;
while(ptr1 && ptr2)
{
if(ptr1->val < ptr2->val)
{
tail->next = ptr1;
ptr1 = ptr1->next;
}
else
{
tail->next = ptr2;
ptr2 = ptr2->next;
}
tail = tail->next;
}
// 4. 总会有一条链表先走完
if(ptr1)
tail->next = ptr1;
if(ptr2)
tail->next = ptr2;
return new_list->next;
}
};
a.核心思想
合并两个有序链表,生成新有序链表。
b.思路
双指针遍历比较,按序拼接节点。
c.步骤
① 处理边界:任一链表为空时直接返回另一链表。
② 创建虚拟头节点简化操作。
③ 双指针遍历两链表,比较节点值,将较小节点接入新链表并移动指针。
④ 将剩余非空链表直接接入新链表尾部。
⑤ 返回新链表头节点(虚拟头的下一节点)。
2.对字节对齐的理解
字节对齐是数据在内存中按特定边界(如2、4、8字节)存储的规则,核心在于
|--------|--------------------------------------|
| 目的 | 提升CPU访问效率,避免跨边界读取导致的性能损耗。 |
| 原则 | 数据类型按其自然对齐值(如int按4字节)存放,不足时填充空白字节。 |
| 影响 | 影响内存占用和访问速度,需在空间效率与访问效率间权衡。 |
| 应用 | 结构体设计、硬件寄存器访问等场景需显式控制对齐方式。 |
希望这些内容对大家有所帮助!
感谢大家的三连支持!