《程序员代码面试指南》第二章 链表问题 两个单链表生成相加链表

题目

两个单链表生成相加链表,例如链表1-2-3 加 8-7-7 生成1-0-0-0

java代码

/**
 * @Description:两个单链表生成相加链表
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 23:23
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter2_10 {

    public Node addLind(Node head1, Node head2) {
        head1 = reverseLink(head1);
        head2 = reverseLink(head2);
        int n1 = 0;
        int n2 = 0;
        int n = 0;
        int ca = 0;
        Node node = null;
        Node head = null;
        Node head1R = head1;
        Node head2R = head2;

        while (head1R != null || head2R != null) {
            n1 = head1R == null ? 0 : head1R.vlaue;
            n2 = head2R == null ? 0 : head2R.vlaue;
            n = n1 + n2 + ca;
            head = new Node(n % 10);
            head.next = node;
            node = head;
            ca = n / 10;
            head1R = head1R.next;
            head2R = head2R.next;
        }
        if (ca != 0) {
            head = new Node(ca);
            head.next = node;
        }
        //复原
        head1 = reverseLink(head1);
        head2 = reverseLink(head2);
        return head;
    }

    public Node reverseLink(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    //测试
    public static void main(String[] args) {
        Chapter2_10 chapter = new Chapter2_10();
        Link link1 = new Link();
        Link link2 = new Link();
        link1.add(3);
        link1.add(2);
        link1.add(1);
        link2.add(7);
        link2.add(7);
        link2.add(8);


        Link.printLink(link1.head);
        Link.printLink(link2.head);

        Node head = chapter.addLind(link1.head, link2.head);
        Link.printLink(head);
    }
}
posted @ 2018-04-06 23:49  lizhouwei  阅读(110)  评论(0编辑  收藏  举报