xiaotiancai893661742 3 years ago
parent 12d9c32d7a
commit 886abe7b28

@ -2,5 +2,74 @@ package zuolaos.jichuban;
public class Code06_ {
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next=new Node(2);
head1.next.next=new Node(3);
Node head2 = new Node(1);
head2.next=new Node(2);
head2.next.next=new Node(9);
Node node = addTowNumbers(head1, head2);
System.out.println(node);
}
private static class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
// 1 2 3 + 7 8 9 9 9 9 9 左边是个位
public static Node addTowNumbers(Node head1, Node head2) {
int len1 = getLen(head1);
int len2 = getLen(head2);
Node l = len1 >= len2 ? head1 : head2;
Node s = l == head1 ? head2 : head1;
Node curL=l;
Node curS=s;
int carry=0;
int curNum=0;
Node last =curL;
while (curS!=null){
curNum=curL.value+curS.value+carry;
curL.value=curNum % 10;
carry=curNum/10;
last=curL;
curL=curL.next;
curS=curS.next;
}
while (curL!=null){
curNum=curL.value+curS.value+carry;
curL.value=curNum % 10;
carry=curNum/10;
last=curL;
curL=curL.next;
}
if(carry>0){
last.next=new Node(1);
}
return l;
}
//求长度
public static int getLen(Node head) {
int count = 0;
while (head != null) {
count++;
head = head.next;
}
return count;
}
}

@ -0,0 +1,52 @@
package zuolaos.jichuban;
public class Code07_ {
public static void main(String[] args) {
Node head1 = new Node(0);
head1.next = new Node(2);
head1.next.next = new Node(3);
Node head2 = new Node(1);
head2.next = new Node(2);
head2.next.next = new Node(9);
Node node = mergeTowLists(head1, head2);
System.out.println(node);
}
private static Node mergeTowLists(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
Node head = head1.value <= head2.value ? head1 : head2;
Node cur1 = head.next;
Node cur2 = head == head1 ? head2 : head1;
Node pre = head;
while (cur1 != null && cur2 != null) {
if (cur1.value <= cur2.value) {
pre.next = cur1;
cur1 = cur1.next;
} else {
pre.next = cur2;
cur2 = cur2.next;
}
pre = pre.next;
}
pre.next = cur1 != null ? cur1 : cur2;
return head;
}
private static class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
}
Loading…
Cancel
Save