题解 | #链表相加(二)#

链表相加(二)

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

具体做法:
申请两个栈空间和一个标记位,然后将两个栈中内容依次相加,将结果倒插入新节点中。

具体过程如下图:


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) {
        // write code here

        LinkedList<Integer> list1 = new LinkedList<>(); //list1栈
        LinkedList<Integer> list2 = new LinkedList<>(); //list2栈
        putData(list1, head1); //入栈
        putData(list2, head2);
        ListNode newNode = null;
        ListNode head = null;
        int carry = 0; //标记进位
        while (!list1.isEmpty() || ! list2.isEmpty() || carry != 0) {
            int x = (list1.isEmpty()) ? 0 : list1.pop();  //依次从栈中取出
            int y = (list2.isEmpty()) ? 0 : list2.pop();
            int sum = x + y + carry; //与进位一起相加
            carry = sum / 10; //更新进位
            //将计算值放入节点
            newNode = new ListNode(sum % 10);
            //更新下一个节点的指向
            newNode.next = head;
            head = newNode;
        }
        return head;

    }
    private void putData(LinkedList<Integer> s1, ListNode head1) {
        if (s1 == null) s1 = new LinkedList<>();
        //遍历节点将其插入栈中
        while (head1 != null) {
            s1.push(head1.val);
            head1 = head1.next;
        }
    }
}


全部评论

相关推荐

面了这么多场试,总有公司总喜欢压力面一个小时面试+手撕,哪里不会就点哪里,说了不会不会还继续追着问不尊重求职者,稍微有些细节记不清了,就开始怀疑项目真实性以及人格让求职者开摄像头但是自己不开,说话声音还贼小,pardon几次就开始不耐烦的不知道这个算不算,手撕的时候,面试官人跑了。。。最后快结束才来
一纸丿繁华丶:你换位思考一下,自己在职场被领导push麻了,身心俱疲,现在有个机会让你放松一下,体验一把上位者的感觉,还能看着那些高学历人才、未来自己的竞争者,抓耳挠腮、手足无措的样子,没给你当场笑出来就不错了,理解一下面试官吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务