登录
  • #刷题
  • #careercup

文科生向文科生讲解递归递归(1)

TonyJang
1238
9
        public static LinkedList<Integer> sum2(LinkedList<Integer> list1, LinkedList<Integer> list2){[br][/br][br][/br]int length1 = list1.size();[br][/br][br][/br]int length2 = list2.size();        [br][/br][br][/br]if(length1!=length2){[br][/br][br][/br]LinkedList<Integer> shortList = length1>length2 ? list2:list1;[br][/br][br][/br]for(int i = Math.abs(length1- length2); i>0; i--){[br][/br][br][/br]shortList.addFirst(0);[br][/br][br][/br]}        [br][/br][br][/br]}        [br][/br][br][/br]LinkedList<Integer> ret = new LinkedList<Integer>();[br][/br][br][/br]int p= sumHelper(ret,list1,list2);[br][/br][br][/br]if(p!=0)[br][/br][br][/br]ret.addFirst(p);[br][/br][br][/br]return ret;[br][/br][br][/br]}[br][/br][br][/br]private static int sumHelper(LinkedList<Integer> result,LinkedList<Integer> list1, LinkedList<Integer> list2){[br][/br][br][/br]if(list1.isEmpty())[br][/br][br][/br]return 0;[br][/br][br][/br]int sum = list1.poll()+list2.poll()+sumHelper(result,list1,list2);[br][/br][br][/br]result.addFirst(sum%10);[br][/br][br][/br]return sum/10;[br][/br][br][/br]}[br][/br][br][/br]
已1->4->6 + 2->7->9=4->2->5为例,

①sum=1+2+sumHelper(result,list1,list2);

②sum=4+7+sumHelper(result,list1,list2);

③sum=6+9+sumHelper(result,list1,list2);

之后list1为空,return 0;返回③,sum=15,result变成5,return 进位1,进入②

sum=4+7+1=12,result变成2,return进位1,进入①

sum=1+2+1=4......

文科生转CS,吐出老血啊,共勉吧

想问一下第五行,LinkedList<Integer> shortList = length1>length2 ? list2:list1;如果list1短一些,那么把list1的内容copy给shortlist,之后shortlist空余位置补0,这样会改变list1的值吗?如果list1或者list2不空位置补0,那么sumHelper(LinkedList<Integer> result,LinkedList<Integer> list1, LinkedList<Integer> list2)这个函数没意义啊
9条回复
热度排序

发表回复