This commit is contained in:
ranwenjie
2021-09-29 19:20:38 +08:00
parent fc99cdfa71
commit 0a43530e64
11 changed files with 187 additions and 58 deletions
+57
View File
@@ -10,6 +10,7 @@
> 自顶向下的递归,自底向上是迭代
## 斐波那契数列
fib(n)=fib(n-1)+fib(n-2)
@@ -67,6 +68,62 @@ int fib(int n) {
```
## 合并有序链表
递归解法
public static LinkedNode mergeSeqLink2(LinkedNode l1, LinkedNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.value < l2.value){
l1.next = mergeSeqLink2(l1.next,l2);
return l1;
}else{
l2.next = mergeSeqLink2(l2.next,l1);
return l2;
}
}
```
非递归解法
```
public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){
if (l1 == null) return l2;
if (l2 == null) return l1;
LinkedNode result = new LinkedNode(0);
LinkedNode tmp = result;
while (l1 != null && l2 != null) {
if (l1.value < l2.value) {
tmp.next = l1;
tmp = tmp.next; //tmp 指针前进
l1 = l1.next ; //l1 前进
} else {
tmp.next = l2;
l2 = l2.next;
tmp = tmp.next;
}
}
if (l1 != null) {
tmp.next = l1;
}
if (l2 != null) {
tmp.next = l2;
}
return result.next;
}
```