zoukankan      html  css  js  c++  java
  • 2. Add Two Numbers

    Description: 

      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.

    Example:

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

     

    思路分析:

      1.首先,数据结构已经定义好了:单链表,Node节点对象包括值和一个指向下一个Node的指针;

      2.需要注意点问题是:1.空节点取值(如:节点求和中有的节点为空);2.进位(如:两个链表最后一个节点求和时产生了进位)

      3.对于逐位求和,第一反应肯定是要循环遍历的,所以代码结构为

        a.循环结束条件:输入的两个单链表都没有next节点了,并且前一个的节点求和没有产生进位。

        b.循环体:理想状况是 每遍历一对节点就完成结果链表(最终方法返回它)对应的一个节点的创建及赋值。

        循环体实现中间有两个点可能有点绕:1.结果链表如何依次增加节点;2.当前循环所生成的节点如何一个个有序的连接到上一个创建的节点上(我当时是有点阻塞,一度想用双向链表)。我的解决方法其实也很直接:新增两个变量分别用来指向循环生成的第一个节点(即结果链表的头节点)和记录当前循环中产生的节点所依附的节点(即上一个节点,因为需要它的next引用指向自己)。


    C#实现:

      

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     public int val;
     5  *     public ListNode next;
     6  *     public ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
    11         ListNode rst = new ListNode(0);
    12         ListNode tmpRst = rst; int flag=0;
    13         bool over = false;
    14         
    15         ListNode tmp1 = l1;
    16         ListNode tmp2 = l2;
    17         while(tmp1 !=null||tmp2 !=null||over ){
    18             int tmpVal1 = tmp1==null?0:tmp1.val;
    19             int tmpVal2 = tmp2==null?0:tmp2.val;
    20              ListNode ln = new ListNode(0);
    21              tmpRst.next = ln;
    22              if(over){
    23                 ln.val = tmpVal1+tmpVal2+1; 
    24              }
    25              else
    26              {
    27                 ln.val = tmpVal1+tmpVal2;
    28              }
    29              over = false;
    30              if(ln.val>=10){
    31                  ln.val-=10;over = true;
    32              }
    33              ln.next = null;
    34              tmpRst = ln;
    35              
    36              if(flag==0){rst = ln;}
    37              tmp1 = tmp1==null?null:tmp1.next;
    38              tmp2 = tmp2==null?null:tmp2.next;
    39              flag++;
    40         }
    41         return rst;
    42         
    43     }
    44 }
  • 相关阅读:
    java中值传递和引用传递
    java中的XML
    java I/O流
    RandomAccessFile类
    java中File类
    Java 理论与实践: 正确使用 Volatile 变量
    eclipse 总弹出 secure storage的解决办法
    安卓表格布局android:collapseColumns,android:shrinkColumns和stretchColumn
    Android关联源码support-v4的问题解决
    关于spring framework最新发布压缩包的下载问题 【非常非常新手帖】
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6529606.html
Copyright © 2011-2022 走看看