题目
两个单链表(singly linked list),每一个节点里面一个0-9的数字, 输入就相当于两个大数了。然后返回这两个数的和(一个新list)。这两个输入的list 长度相等。 要求是:1. 不用递归。2. 要求算法在最好的情况下,只遍历两个list一次, 最差的情况下两遍。
实现代码:
public class AddSinglyLinkList {
public static void main(String[] args) {
int[] a = {1,1,1};
int[] b = {1,1,1};
int[] a2 = {1, 2, 3};
int[] b2 = {1, 2, 8};
int[] a3 = {1, 2, 3, 4, 5};
int[] b3 = {1, 7, 6, 5, 9};
Node head1 = makeLinkedList(a3);
Node head2 = makeLinkedList(b3);
System.out.println("****************");
printNodeList(head1);
printNodeList(head2);
System.out.println("****************");
Node r = addSinglyList(head1, head2);
printNodeList(r);
}
static Node addSinglyList(Node h1, Node h2) {
Node p,q;
p = h1;
q = h1.next;
h2 = h2.next;
while(q != null) {
q.data = q.data + h2.data;
//System.out.println(q.data);
if(q.data > 9) {
q.data = q.data%10;
p.data ++;
while(p.next != q){
p = p.next;
p.data = 0;
}
}else if(q.data != 9) {
p = p.next;
}
q = q.next;
h2 = h2.next;
}
return h1;
}
static void printNodeList(Node h) {
Node n = h.next;
while(n != null) {
System.out.print(n.data + " ");
n = n.next;
}
System.out.println();
}
static Node makeLinkedList(int[] a){
Node head = new Node(0, null);
Node p = head;
for(int i: a) {
Node temp = new Node(i, null);
p.next = temp;
p = temp;
}
return head;
}
}
class Node{
int data;
Node next;
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}