两个链表相加,翻转链表

将两个链表进行翻转,然后遍历链表进行相加

翻转链表:

reverseList(head){

pre = null;//将遍历到的节点放在这个空节点的前面

cur = head;

while(cur != null){

  temp  = cur.next;//断开链表前,存一下下一个节点

  cur.next  = pre;

  pre = cur;

  cur = pre;

  }

return pre;

遍历相加:

add(head1,head2){

  head1 = reverseList(head1);

  head2 = reverseList(head2);

  res = new Node(-1);

  new head = res;

  记录进位

  int carry = 0;

  while(head1 != null || head != null || carry != 0){

    int val1 = (head1 == null)?0:head1.val;

    同理val2

    int temp = val1 + val2 + carry;

    carry = temp/10;

    temp %= 10;

    head.next = new Node(temp);

    head = head.next; 

    if(head1 != null){head1 = head1.next}

    if(head2 != null){head2 = head2.next}

  }  

return reverseList(head);

 

原文地址:https://www.cnblogs.com/materialdog/p/17270033.html