链表相加(一)

链表相加(一)

https://www.nowcoder.com/practice/521d83306d964c1188639033eb59621d?tpId=196&tqId=40273&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj&difficulty=undefined&judgeStatus=undefined&tags=580&title=

链表相加(一)

思路:

1.建立一个新的虚的头结点

2.只要两个链表中还有节点并且进位不为0,就需要进行相加操作

代码:

import java.util.*;

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

public class Solution {
    public ListNode ListAdd (ListNode l1, ListNode l2) {
        //创建一个新链表的虚的头结点
       ListNode dummynode=new ListNode(-1);
       ListNode cur=dummynode;
       int res=0,t1,t2,temp,sum=0;
       //只要链表的还有节点或者进位不为0,就需要进行相加
       while(l1!=null||l2!=null||res!=0){
            t1=(l1==null)?0:l1.val;
            t2=(l2==null)?0:l2.val;
            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }
            sum=res+t1+t2;
            ListNode p=new ListNode(sum%10);
            cur.next=p;
            cur=cur.next;
            res=sum/10;
       }
       return dummynode.next;
    }
}
全部评论

相关推荐

做个有文化的流氓:不想当将军的士兵不是好士兵
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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