美文网首页
加法合并链表

加法合并链表

作者: Dynamic_2018 | 来源:发表于2017-11-10 15:35 被阅读2次

    题目:

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    思路:

    没有要求时间空间复杂度,单纯链表操作。而且给出了Node的定义。建一个临时的head,指向第一个Node,根据加法算出后面的Node。再返回head.next即可。注意一些特殊情况以免漏掉一些case。

    代码:(有点冗余,但是勉强ac了)

    /**
    * Definition for singly-linked list.
    * public class ListNode {
    *     int val;
    *     ListNode next;
    *     ListNode(int x) { val = x; }
    * }
    */
    class Solution {
       public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           ListNode head = new ListNode(0);
           ListNode temp = head;
           int flag = 0;
           while(l1!=null&&l2!=null){
               if((l1.val+l2.val+flag)>9){
                   temp.next = new ListNode(l1.val+l2.val-10+flag);
                   temp = temp.next;
                   flag = 1;
               }else {
                   temp.next = new ListNode(l1.val+l2.val+flag);
                   temp = temp.next;
                   flag = 0;
               }
               l1 = l1.next;
               l2 = l2.next;
           }
           while(l1!=null){
               if((l1.val+flag)>9){
                    temp.next = new ListNode(l1.val+flag-10);
                    temp = temp.next;
                    flag = 1;
               }
               else{
                   temp.next = new ListNode(l1.val+flag);
                    temp = temp.next;
                    flag = 0;
               }
               l1 = l1.next;
              
           } 
            while(l2 !=null){
               if((l2.val+flag)>9){
                    temp.next = new ListNode(l2.val+flag-10);
                    temp = temp.next;
                    flag = 1;
               }
               else{
                   temp.next = new ListNode(l2.val+flag);
                    temp = temp.next;
                    flag = 0;
               }
               l2 = l2.next;
               
           }
           if(flag == 1){
               temp.next = new ListNode(1);
           }
           return head.next;
       }
    }
    

    相关文章

      网友评论

          本文标题:加法合并链表

          本文链接:https://www.haomeiwen.com/subject/sdibmxtx.html