题解 | 链表相加(二)

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode reverseList(ListNode head1){
        ListNode newList = null;
        ListNode cur  = head1;
        ListNode next;
        while(cur!=null){
            next = cur.next;
            cur.next = newList;
            newList = cur;
            cur = next;
        }
        return newList;
    }
    public ListNode dealListUseStack(ListNode head1){
        Stack<ListNode> stack1 = new Stack<>();
        ListNode p = head1;
        while(p!=null){
            stack1.push(p);
            p = p.next;
        }
        ListNode newList = stack1.pop();
        ListNode m = newList;
        while(!stack1.isEmpty()){
            ListNode node = stack1.pop();
            m.next = node;
            m = node;
        }


        //最后要保证链表的最后指向空
        m.next = null;

        return newList;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        ListNode newList1= dealListUseStack(head1);
        ListNode newList2 = dealListUseStack(head2);
        int carry = 0;
        ListNode p = newList1;
        ListNode q = newList2;
        ListNode relList = null;
        int value1,value2,total,value;
        while(p!=null || q!=null ||carry!=0){
            if (p!=null){
                value1 = p.val;
            }
            else{
                value1 = 0;
            }
            if (q!=null){
                value2 = q.val;
            }
            else{
                value2 = 0;
            }
            total  = value1 + value2 + carry;
            value = total % 10;
            carry = total / 10;
            ListNode newNode = new ListNode(value);
            newNode.next = relList;
            relList = newNode;
            if (p!=null){
                p = p.next;
            }
            if(q!=null){
                q = q.next;

            }
        }
        return relList;
    }
}

出现了两个问题 1.newList 初始化为空 然后又将m 指向newList ,其实是将m初始化为空,导致,后面的追加是有问题的。因此,应该将newList 初始化时指定一个节点。

2.链表的最后要求是要指向一个null

3.stack的用法 Stack<类型> stack1 = new Stack <>(); 栈存在pop(),peek(),isEmpty()方法

全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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