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

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

这道题的解题思路主要还是利用栈的方式,将两个链表的结点拿出来,然后由栈保存
通过遍历的方式,弹出每个栈最后一个结点,并且判断当前结点值的大小。
同时使用头插法将每一个新结点插入链表。
同时判断当前进位的标志位是否在仍然大于0,如果是,新建结点使用头插法插入
/*class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
export function addInList(head1: ListNode, head2: ListNode): ListNode {
    // write code here
    let arr1=[]
    let arr2 =[]
    let p1=head1
    let p2=head2
    
    while(p1) {
        arr1.push(p1)
        p1=p1.next
    }
    
    while(p2) {
        arr2.push(p2)
        p2=p2.next
    }
    let val =0
    let tem=0
    let lnode = null
    let nHead = lnode
    while(arr1.length!=0||arr2.length!=0) {
        /*if()
        val = arr1.pop().val+arr2.pop().val*/
        val = tem
        //获得累加值
        if(arr1.length!=0) val+=arr1.pop().val
        if(arr2.length!=0) val+=arr2.pop().val
        
        //插入当前链表
        let tnode = new ListNode(val%10)
        tnode.next = lnode
        lnode = tnode
        //进位节点
        tem = Math.floor(val/10)
    }
    if(tem>0) {
        let node = new ListNode(tem)
        node.next = lnode
        lnode = node
    }
    return lnode
}


全部评论

相关推荐

01-11 08:47
门头沟学院 Java
choumoduji...:读研的目的就是为了以最快的速度和最低的要求完成“学校”规定的毕业标准,而不是所谓课题组的要求
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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