描述 假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。 给定两个这种链表,请生成代表两个整数相加值的结果链表。 例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。 示例1 输入: [9,3,7],[6,3] 复制 返回值: {1,0,0,0}
public class 两个链表生成相加链表 {
public class ListNode {
int val;
ListNode next = null;
public ListNode(int i) {
val = i;
}
}
public ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode pre = null, curr = head;
while(curr != null){
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
public ListNode addInList (ListNode head1, ListNode head2) {
ListNode h1 = reverse(head1), h2 = reverse(head2);
ListNode temp = new ListNode(-1);
ListNode curr = temp;
boolean flag = false;
int t = 0;
while(h1 != null || h2 != null){
int node1 = h1 != null ? h1.val : 0;
int node2 = h2 != null ? h2.val : 0;
int total = node1 + node2;
if(flag){
total += 1;
}
if(total / 10 > 0){
flag = true;
}else{
flag = false;
}
curr.next = new ListNode(total % 10);
if(h1 != null){
h1 = h1.next;
}
if(h2 != null){
h2 = h2.next;
}
curr = curr.next;
}
if(flag){
curr.next = new ListNode(1);
}
return reverse(temp.next);
}
}
|