汉诺塔问题
面试题 08.06. 汉诺塔问题 - 力扣(LeetCode)

第一步

第二步
将A中的剩下的那个移到C中

第三步
将B中的借助A移到C中

总体的逻辑就是这样,看成三部分
class Solution {
public void hanota(List<Integer> a, List<Integer> b, List<Integer> c) {
dfs(a,b,c,a.size());
}
public void dfs(List<Integer> a, List<Integer> b, List<Integer> c,int n){
if(n==1){
c.add(a.remove(a.size()-1));
return ;
}
dfs(a,c,b,n-1);
c.add(a.remove(a.size()-1));
dfs(b,a,c,n-1);
}
}
合并两个有序列表
fna
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
if(list1.val<=list2.val){
list1.next=mergeTwoLists(list1.next,list2);
return list1;
}else{
list2.next=mergeTwoLists(list2.next,list1);
return list2;
}
}
}
反转链表
可以使用递归的方法,也可以使用链表循环的方法,进行顺序的修改

法一:递归进行逆序

class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode cur=head;
ListNode newHead=reverseList(cur.next);
cur.next.next=cur;
cur.next=null;
return newHead;
}
}
法二:链表循环进行逆序
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null ||head.next==null){
return head;
}
ListNode cur=head.next;
head.next=null;
ListNode curN=cur.next;
ListNode prev=head;
while(cur.next!=null){
cur.next=prev;
prev=cur;
cur=curN;
curN=curN.next;
}
cur.next=prev;
return cur;
}
}
两两交换链表中的节点

class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode newHead=swapPairs(head.next.next);
ListNode cur=head.next;
cur.next=head;
head.next=newHead;
return cur;
}
}
pow(x,n)


class Solution {
public double myPow(double x, int n) {
long N=n;
return N<0?pow(1.0/x,-N):pow(x,N);
}
public double pow(double x, long n){
if(n==0){
return 1.0;
}
double tem=pow(x,n/2);
return n%2==0?tem*tem:tem*tem*x;
}
}
766

被折叠的 条评论
为什么被折叠?



