zoukankan      html  css  js  c++  java
  • 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. 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.

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

    解题思路:

    定义三个ListNode l1、l2,result,其中result为return语句的输出,l1、l2为传入的参数。

    将l1赋值给result,执行result.val+=l2.val,然后l1作为指针一级一级往下走,直到走到l2.next为null。当然,之间会有不少边界条件,自己debug一下就好。

    Java代码如下:

    public class Solution {
          static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        	ListNode result=l1;
        	while(true){
        		l1.val+=l2.val;
        		if(l1.val>=10){
        			l1.val%=10;
        			if(l1.next==null) l1.next=new ListNode(1);
        			else l1.next.val+=1;
        		}
        		
    		if(l2.next==null){
    			ListNode l3=l1.next;
    			while(true){
    				if (l3==null) break;
    				if(l3.val==10){
    					l3.val%=10;
    	    			if(l3.next==null) l3.next=new ListNode(1);
    	    			else l3.next.val+=1;
    				}
    				l3=l3.next;
    			}
    			break;
    		}
    		
        	l2=l2.next;
        	if(l1.next==null){
        		l1.next=new ListNode(0);
        	}
        	l1=l1.next;
        	}
        	return result;
        	
        }
    }
    

     C++

     1 class Solution {
     2 public:
     3     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
     4         ListNode* res=l1;
     5         while (true) {
     6             l1->val += l2->val;
     7             if (l1->val >= 10) {
     8                 l1->val %= 10;
     9                 if (l1->next == NULL) 
    10                     l1->next = new ListNode(1);
    11                 else l1->next->val += 1;
    12             }
    13 
    14             if (l2->next == NULL) {
    15                 ListNode* l3 = l1->next;
    16                 while (true) {
    17                     if (l3 == NULL) break;
    18                     if (l3->val == 10) {
    19                         l3->val %= 10;
    20                         if (l3->next == NULL) l3->next = new ListNode(1);
    21                         else l3->next->val += 1;
    22                     }
    23                     l3 = l3->next;
    24                 }
    25                 break;
    26             }
    27 
    28             l2 = l2->next;
    29             if (l1->next == NULL) {
    30                 l1->next = new ListNode(0);
    31             }
    32             l1 = l1->next;
    33         }
    34         return res;
    35     }
    36 };
  • 相关阅读:
    HTML-代码定义
    数组
    for。。。for嵌套if,if嵌套for。
    输入年月日, 判断输入的是否正确
    日期功能
    方程
    5.8 一维数组
    5.9 二维数组
    5.7 类
    5.4穷举,迭代
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4451783.html
Copyright © 2011-2022 走看看