算法擼一遍,從簡單的開始。算法
作leetcode題目的時候,常常百度答案,但感受大多不是我想要的,不少我不能理解。如今也作了一些算法題,哪些並非很深奧,但須要一些技巧,簡單的算法題更多的是經驗值。這裏,開啓算法題篇章。給本身記憶,但願不要誤人子弟。bash
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,而且它們的每一個節點只能存儲 一位 數字。ui
若是,咱們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。spa
您能夠假設除了數字 0 以外,這兩個數都不會以 0 開頭。code
示例:leetcode
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
緣由:342 + 465 = 807複製代碼
看完題目,簡單點理解就是 1+1=2的題目。只不過是用鏈表存的數據class
1:循環鏈表,取出全部數據,兩個鏈表都爲空爲止百度
2:同位數相加,大於10要取餘進一List
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);//用來存儲
ListNode listNode2 = listNode;
int z = 0 ;
while (l1 != null && l2 != null){
int x ;
int y ;
x = l1 != null ? l1.val : 0; //若是爲空的話 用0賦值
y = l2 != null ? l2.val : 0;
listNode2.next = new ListNode((x + y + z) % 10);//計算取餘
listNode2 = listNode2.next;
z = (x + y + z) >= 10 ?1:0;
if (l1 != null)l1 = l1.next ; //下一位
if (l2 != null)l2 = l2.next ;
}
if (z > 0 ){
listNode2.next = new ListNode(z);
}
return listNode.next ;
}複製代碼
其餘代碼循環
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}複製代碼
public static void main(String[] age){
ListNode listNode1 = new ListNode(2);
ListNode listNode2 = new ListNode(4);
ListNode listNode3 = new ListNode(3);
listNode2.next = listNode3;
listNode1.next = listNode2;
ListNode listNode4 = new ListNode(5);
ListNode listNode5 = new ListNode(6);
ListNode listNode6 = new ListNode(4);
listNode5.next = listNode6;
listNode4.next = listNode5;
ListNode listNode = addTwoNumbers(listNode1, listNode4);
while (listNode != null){
System.out.println(listNode.val);
listNode = listNode.next;
}
}複製代碼