将两个链表相加,返回新的链表,然后遍历输出
package LK;
public class 两个链表相加 {
public static class Lode {
public int val;
public Lode next;
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public Lode getNext() {
return next;
}
public void setNext(Lode next) {
this.next = next;
}
public Lode(int val) {
this.val = val;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
}
public static int listLength(Lode head) {
int length = 0;
while (head != null) {
head = head.next;
length++;
}
return length;
}
public static Lode Add(Lode head1, Lode head2) {
int len1 = listLength(head1);
int len2 = listLength(head2);
Lode l = len1 >= len2 ? head1 : head2;
Lode s = l == head1 ? head2 : head1;
Lode curL = l;
Lode curS = s;
Lode last = curL;
int carry = 0;//进位
int curNum = 0;
while (curS != null) {
curNum = curL.val + curS.val + carry;
curL.val = curNum % 10;
carry = curNum / 10;
last = curL;
curL = curL.next;
curS = curS.next;
}
while (curL != null) {
curNum = curL.val + carry;
curL.val = curNum % 10;
carry = curNum / 10;
last = curL;
curL = curL.next;
}
if (carry != 0) {
last.next = new Lode(1);
}
return l;
}
public static void main(String[] args) {
Lode l1=new Lode(1);
l1.next=new Lode(2);
Lode l2=new Lode(1);
l2.next=new Lode(9);
l1=Add(l1,l2);
while(l1!=null){
System.out.println(l1.val);
l1=l1.next;
}
}
}
Comments 2 条评论
博主 gold ira companies
Everything posted made a lot of sense. But, consider this, suppose you
typed a catchier post title? I ain’t suggesting your content isn’t good., but suppose you added
a post title to maybe get a person’s attention? I mean 算法学习,脑洞大开 –
MAGICAL is a little boring. You might glance at Yahoo’s home page and note how they write news titles to grab people to open the links.
You might add a related video or a related pic or two to grab people interested about everything’ve written. Just
my opinion, it would make your blog a little bit more interesting.
博主 Magical
@gold ira companies OK, thank you for your suggestion!As a student, I will continue to learn and make corrections.