• (LinkedList)2. 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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         if (l1 == null)
    			return l2;
    		if (l2 == null)                  //这题看起来简单,但是花了很长时间啊,链表要遍历几次,但是这样写代码最短?实在不想再写了
    			return l1;
    		int temp = 0;
    		ListNode p = l1;
    		ListNode q = l2;
    		ListNode longList = l1;
    		ListNode la = l1;
    		while (p != null && q != null) {
    			p = p.next;
    			q = q.next;
    		}
    		if (q == null) {
    			q = l1;
    			p = l2;
    			longList = l1;
    		} else {
    			q = l2;
    			p = l1;
    			longList = l2;
    		}
    		while (p != null && q != null) {
    			if (p.val + q.val + temp >= 10) {
    				q.val = p.val + q.val + temp - 10;
    				temp = 1;
    			} else {
    				q.val = q.val + p.val + temp;
    				temp = 0;
    			}
    			p = p.next;
    			q = q.next;
    		}
    		while (q != null) {
    			if (q.val + temp >= 10) {
    				q.val = q.val + temp - 10;
    				temp = 1;
    			} else {
    				q.val = q.val + temp;
    				temp = 0;
    			}
    			q = q.next;
    		}
    		if (temp == 1) {
    			ListNode last = new ListNode(1);
    			last.next = null;
    			p = longList;
    			while (p.next!= null)
    				p = p.next;
    			la = p;
    			la.next = last;
    		}
    
    		return longList;
        }
    }
    

      

  • 相关阅读:
    开发应用资料大全
    shutil库文件的操作
    搭建appium自动化测试环境
    python实现语音录入识别
    go解析markdown转成html
    go指定分隔符格式化时间
    go语言中使用正则表达式
    django_websocket实现简单聊天室
    PyQt5显示日期选择框,获取日期保存文件
    python解决迅雷下载限制的方法
  • 原文地址:https://www.cnblogs.com/kydnn/p/5376751.html
Copyright © 2020-2023  润新知