Leetcode学习计划-算法入门第10天
主题:递归、回溯
题目21:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
方案:确定递归条件,两个链表头部值较小的一个节点与剩下元素的 merge 操作结果合并。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(list1==nullptr){
return list2;
}
else if(list2==nullptr){
return list1;
}
else if(list1->val<=list2->val){
list1->next=mergeTwoLists(list1->next,list2);
return list1;
}
else{
list2->next=mergeTwoLists(list1,list2->next);
return list2;
}
}
};
题目206:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
方案:迭代和递归两种
递归:
主要包括终止条件和递归过程。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}