目录
1.剑指Offer
面试题24:反转链表
题目描述:输入一个链表,反转链表后,输出新链表的表头。
思路:考虑代码鲁棒性
代码:
//迭代
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* ReverseNode=nullptr;
ListNode* pPrev=nullptr;
ListNode* pNode=pHead;
while(pNode!=nullptr){
ListNode* pNext=pNode->next;
if(pNext==nullptr){
ReverseNode=pNode;
}
pNode->next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return ReverseNode;
}
};
//递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr){
return head;
}
ListNode* p=reverseList(head->next);
head->next->next=head;
head->next=nullptr;
return p;
}
};
面试题25:合并两个排序链表
题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:递归实现
代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==nullptr){
return pHead2;
}
if(pHead2=&#