目录
基础:
一、递归
题目:
1、链表反转
2、合并两个有序链表
class Solution{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
if(l1 == nullptr){
return l2;
}else if(l2 == nullptr){
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;
}
}
};
3、两个数相加
LeetCode-两数相加(java递归)_可口可乐-CSDN博客
4、素数统计个数
一、链表
单链表
//接口singleList.h
#ifndef _SINGLELIST_H
#define _SINGLELIST_H
struct SNode //结点的基本数据类型
{
int data;
SNode *PNext;
};
typedef unsigned int UINT
typedef SNode* ListNode;
class
1、链表反转
将单链表的链表的链接顺序反转过来
1、迭代
/** * 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* reverseList(ListNode* head) { ListNode *prevNode , *nextPoint; prevNode = nullptr; ListNode *curr = head; while(curr) { nextPoint = curr->next; curr->next = prevNode; prevNode = curr; curr = nextPoint; } return prevNode; } };
2、递归
首先一直迭代到链尾也就是递归判断的准则,然后再逐层返回处理到开头。总的来说,链表反转操作的顺序对于迭代而言是从链头到链尾,对于递归而言是链尾到链头。
class Solution { public: ListNode* reverseList(ListNode* head) { if(head == nullptr || head -> next == nullptr) return head; ListNode* newHead = reverseList(head->next); head ->next ->next = head; head -> next = nullptr; return newHead; } };