1、题目描述:给出链表的头节点,请你反转链表,并返回反转之后的链表
实例:输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
提示:链表中的节点的数目范围是[0,5000]
解题过程:
首先定义一个cur指针,指向头结点,再定义一个pre指着,初始化为NULL
struct ListNode{
int val;
ListNode*next;
ListNode(int x):val(x),next(NULL){}
};
//反转链表
ListNode* ReverseList(ListNode*head)
{
ListNode*temp;
ListNode*cur=head;
ListNode*pre=NULL:
while(cur)
{
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
第二种方法递归法,递归三部曲:确定返回类型、确定终止条件、确定单层循环的逻辑
//递归法
ListNode* Reverse(ListNode* pre,ListNode*cur)
{
//结束条件
if (cur == NULL)return pre;
//单层递归的逻辑
ListNode* temp = cur->next;
cur->next = pre;
return Reverse(cur, temp);
}
ListNode* ReverseList(ListNode* head)
{
return Reverse(NULL, head);
}
ListNode* reverse(ListNode* cur, ListNode* pre)
{
//确定终止条件
if (cur == NULL)return pre;
//确定单层循环的逻辑
ListNode* temp = cur->next;
cur->next = pre;
return reverse(temp, cur);
}
ListNode* reverseList(ListNode* head)
{
return reverse(head, NULL);
}
2、题目:将两个升序链表合并称一个新的升序链表并返回,新链表时通过拼接给定的链表的所有节点组成的
实例:输入L1=[1,2,4],L2=[1,3,4],输出[1,1,2,3,4,4]
解决思路:递归法
ListNode* mergeTwoLists(ListNode* L1, ListNode* L2)
{
if (L1 == NULL)return L2;
else if (L2 == NULL)return L1;
//判断哪一个链表的头结点的值更小,然后递归地确定下一个添加到结果中的节点
else if (L1->val < L2->val)
{
L1->next = mergeTwoLists(L1->next, L2);
return L1;
}
else
{
L2->next = mergeTwoLists(L1, L2->next);
return L2;
}
}