链表有序递增,每个节点都是0-9内的数字,相加的时候涉及进位问题,如:
链表1:
123
链表2:
789
结果链表:
81012
思路:同时遍历2个链表,计算2个链表同一位置的节点之和,判断是否<10,如果小于不进位,直接new个node节点
如果>10 那么涉及进位问题,需要前插进位的1节点,next节点为和10取余
/**
* @author yuchen
* @version 1.0
* @date 2020-05-26 11:20
*/
public class NodePlus {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.next = node2;
node2.next = node3;
Node node7 = new Node(7);
Node node8 = new Node(8);
Node node9 = new Node(9);
node7.next = node8;
node8.next = node9;
Node node = plusNode(node1,node7);
while (node!=null){
System.out.println(node.data);
node = node.next;
}
}
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public static Node plusNode(Node head1,Node head2){
if(head1==null && head2!=null){
return head2;
}
if(head2==null && head1!=null){
return head1;
}
int jinwei = 0;
Node cur1Node = head1;
Node cur2Node = head2;
Node pre = null;
while (cur1Node!=null){
cur1Node.data += jinwei;
if(cur2Node!=null){
cur1Node.data = cur1Node.data + cur2Node.data;
cur2Node = cur2Node.next;
}
jinwei = cur1Node.data / 10;
cur1Node.data = cur1Node.data % 10;
pre = cur1Node;
cur1Node = cur1Node.next;
}
while (cur2Node!=null){
cur2Node.data += jinwei;
jinwei = cur2Node.data / 10;
cur2Node.data = cur2Node.data % 10;
pre.next = cur2Node;
pre = pre.next;
cur2Node = cur2Node.next;
}
if (jinwei > 0){
Node node = new Node(jinwei);
pre.next = node;
}
return head1;
}
}