两个单链表生成相加链表

题目:假设链表中每一个节点的值0~9之间,那么链表整体就可以代表一个整数。

例如:9->3->7,可以代表整数937。
给定两个这种链表的头节点 head1 和 head2,请生成代表两个整数相加值的结果链表。
例如:链表 1 :9->3->7,链表 2 :6->3,最后生成的结果链表为 1->0->0->0。

方法:
1、将两个链表分别从左到右遍历,遍历过程中将值压栈,这样就生成了两个链表节点值的逆序栈,分别表示为 s1 和 s2 。如:7、3、9 和 3、6
2、将 s1 和 s2 同步弹出,这样就相当于两个链表从低位到高位依次相加(模拟加法运算),同时关注进位用 ca 表示。
     例如 : s1 先弹出 7,s2 先弹出3,这一步相加结果为 10,产生进位,令 ca = 1,然后生成一个节点值为 0 的新节点,记作 new1; s1再弹出 3,s2 再弹出 6,这时进位为 1,所以这一步相加结果为 10,继续产生进位,仍令 ca = 1,然后生成一个节点值为 0 的新节点记作 new2,令 new2.next = new1;s1继续弹出 9 ,s2为空,这是 ca = 1,这一步相加结果为 10,仍令 ca = 1,然后生成一个节点值为 0 的新节点,记作 new3,令 new3.next = new2。
3、当 s1 和 s2 为空时还要关注一下 ca 是否为 1 ,如果为 1 如步骤 2 所示那样还要生成一个值为 1 的节点 new4, 令 new4.next = new3.
4、返回新链表即可。
public class Node{
             public Integer value ;
             public Node next ;
            
             public Node(Integer data){
                   this . value = data;
            }
      }
      
       public Node addList(Node head1, Node head2){
            Stack<Integer> s1 = new Stack<Integer>();
            Stack<Integer> s2 = new Stack<Integer>();
            
             while (head1 != null ){
                  s1.push(head1. value );
                  head1 = head1. next ;
            }
             while (head1 != null ){
                  s1.push(head1. value );
                  head1 = head1. next ;
            }
             int ca = 0;
             int n1 = 0;
             int n2 = 0;
             int n = 0;
            Node node = null ;
            Node pre = null ;
             while (!s1.isEmpty() || !s2.isEmpty()){
                  n1 = s1.isEmpty() ? 0 : s1.pop();
                  n2 = s2.isEmpty() ? 0 : s2.pop();
                  n = n1 + n2 + ca;
                  pre = node;
                  node = new Node(n % 10);
                  node. next = pre;
                  ca = n / 10;
            }
             if (ca == 1){
                  pre = node;
                  node = new Node(1);
                  node. next = pre;
            }
             return node;
      }

图片介绍:

  参考资料:《程序员面试代码指南》左程云 著

猜你喜欢

转载自blog.csdn.net/young_1004/article/details/80586525
今日推荐