题解 | #两个链表生成相加链表#

两个链表生成相加链表

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

反转链表

反转链表可以参考我的 https://blog.nowcoder.net/n/44a956fd6b7044d5928c70bc63175507

讲一下加法的模拟
	例如:  a b c d     arr1
    		  e f g     arr2
        设进位的大小为t
        	每一轮只要 t += (arr1[i] + arr2[i]) 没有的情况下,去掉即可
            结果集.push(t % 10),t /= 10
            如果最后进位t不为0,继续操作即可
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        //反转链表 head1
        ListNode tmp = null;
        ListNode a = head1;
        ListNode b = head1.next;
        while(b != null){
            tmp = b.next;
            b.next = a;
            a = b;
            b = tmp;
        }
        head1.next = null;
        head1 = a;
        tmp = null;
        a = head2;
        b = head2.next;
        while(b != null){
            tmp = b.next;
            b.next = a;
            a = b;
            b = tmp;
        }
        ////反转链表 head2
        head2.next = null;
        head2 = a;
        //构造结果集
        boolean ok = false;
        ListNode ret = null;
        ListNode head3 = null;
        int t = 0;
        while(head1 != null || head2 != null || t != 0){
            if(head1 != null){
                t += head1.val;
                head1 = head1.next;
            }
            if(head2 != null){
                t += head2.val;
                head2 = head2.next;
            }
            //是不是第一次添加点的操作
            if(!ok){
                ret = new ListNode(t % 10);
                head3 = ret;
                ok = true;
            }else {
                ret.next = new ListNode(t % 10);
                ret = ret.next;
            }
            t /= 10;
        }
        //反转链表 结果集
        if(ret == null)return null;
        tmp = null;
        a = head3;
        b = head3.next;
        while(b != null){
            tmp = b.next;
            b.next = a;
            a = b;
            b = tmp;
        }
        head3.next = null;
        return a;
    }
}
全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务