• 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

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11         ListNode c1 = l1;//定义两个指针变量 c1 c2
    12         ListNode c2 = l2;
    13         ListNode head = new ListNode(0);//定义一个新链表的头结点
    14         ListNode d = head;//新链表的指针变量
    15         int sum = 0;
    16         while(c1 != null || c2 != null) {
    17             if(c1 != null) {
    18                 sum = sum + c1.val;
    19                 c1 = c1.next;
    20             }
    21             if(c2 != null) {
    22                 sum = sum + c2.val;
    23                 c2 = c2.next;
    24             }
    25             d.next = new ListNode(sum%10);
    26             d = d.next;
    27             sum = sum /10;
    28         }
    29         if(sum == 1) {
    30             d.next = new ListNode(1);
    31         }
    32         return head.next;
    33         
    34         
    35     }
    36 }
  • 相关阅读:
    VirtualBox 创建com对象失败
    大数据(十)
    HITCON 2014 已開始征求投稿计划书
    CSS
    工具
    工具
    Linux
    Python
    JavaScript
    JavaScript
  • 原文地址:https://www.cnblogs.com/leehfly/p/4952113.html
Copyright © 2020-2023  润新知