1. 两数相加
两数相加(尾插法)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = new ListNode(sum % 10);
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if(carry) tail->next = new ListNode(carry);
return head;
}
};
2. 删除链表的倒数第N位
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//删除倒数第n个节点,前一节点要指向倒数n+1
ListNode* p1 =head;
ListNode* p2 =head;
for(int i=0;i<n;i++) p2=p2->next;
if(!p2) return head->next;//对于第一个点被删除的处理,也可以设一个头结点统一所有操作
while(p2->next){
p1=p1->next;
p2=p2->next;
}
p1->next=p1->next->next;
return head;
}
};
2. 合并两个有序链表
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* preHead = new ListNode(-1);
ListNode* prev = preHead;
while (l1&&l2) {
if (l1->val < l2->val) {
prev->next = l1;
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
prev->next = l1 == nullptr ? l2 : l1;
return preHead->next;
}
};
3. 反转链表
//递归(从后往前进行尾插)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next)
return head;//返回初始为空的节点以及单个节点
ListNode* newHead = reverseList(head->next);
head->next->next = head;//head->next变成了尾结点,将head放在尾结点后
head->next = nullptr;
return newHead;
}
};
//头插法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*pre= new ListNode();
ListNode*node= head;
while(head!=NULL){
head=head->next;
node->next=pre->next;
pre->next=node;
node = head;
}
return pre->next;
}
};
5. 判断回文链表(递归)
public:
bool recursivelyCheck(ListNode* currentNode) {
if (currentNode != nullptr) {
if (!recursivelyCheck(currentNode->next))
return false;
if (currentNode->val != frontPointer->val)
return false;
frontPointer = frontPointer->next;
}
return true;
}
bool isPalindrome(ListNode* head) {
frontPointer = head;
return recursivelyCheck(head);
}
};
6. 相交链表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == nullptr ? headB : pA->next;
pB = pB == nullptr ? headA : pB->next;
}
return pA;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了