醫生說我很健康真是太好了呢,今日題目如下
**題號:2 標題:Add Two Numbers 難度:Medium
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
我的程式碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int count = 0;
int a,b;
ListNode result = new ListNode();
ListNode result2 = new ListNode();
ListNode head = result;
ListNode tail = result;
int c = 0;
while(l1 != null || l2 != null){
ListNode temp = new ListNode();
if(l1 != null && l2 != null){
a=l1.val; b=l2.val;
}else if(l1 == null){
a=0;b=l2.val;
}else{
a=l1.val; b=0;
}
System.out.println(a +"," +b+","+count);
temp.val = (a+b+count)%10;
//System.out.println(temp.val);
if(head==null){
head = temp;
tail = temp;
System.out.println(temp.val);
}else{
tail.next = temp;
tail =temp;
}
if((a+b+count)/10 > 0){
count = 1;
}else{
count = 0;
}
if(l1 !=null){
l1 = l1.next;
}
if(l2 !=null){
l2 = l2.next;
}
if(l2 ==null && l1 ==null && count ==1){
ListNode temp2 = new ListNode();
temp2.val = 1;
tail.next = temp2;
tail =temp2;
}
}
result2 = result.next;
return result2;
}
}
花比較久的時間在
linklist上網查了一下怎麼用,雖然修修改改是把這題寫完了,之後有時間要來好好瞭解linklist怎麼用阿
DAY14心得
我還得念書,勸說自己一點躺平