[LeetCode]2.Add Two Numbers

来源:互联网 发布:怎么下载excel软件 编辑:程序博客网 时间:2024/06/11 14:49

一、问题描述
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

二、问题分析及源代码
两个链表相加得到一个新的链表,这题的关键在于进位数的处理。

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    int c=0;//代表进位数    struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode)),*p=l1,*q=l2;    res->val=0;    res->next=NULL;    struct ListNode *head = res;    while(p!=NULL||q!=NULL){        res->val=(res->val)+(p==NULL?0:(p->val))+(q==NULL?0:(q->val));//条件运算符的使用大大缩短了代码的长度,但在这里因为->的        //存在要注意运算符之间的优先级问题        if((res->val)<10){            c=0;        }else{            c=1;            (res->val)-=10;        }        printf("%d ",res->val);        if(((p!=NULL)?((p->next)!=NULL):0)||((q!=NULL)?((q->next)!=NULL):0)||(c==1)){//1.对p、q、p->next、q->next进行判断            res->next = (struct ListNode*)malloc(sizeof(struct ListNode));            res->next->val = c;            res->next->next = NULL;            res = res->next;        }        if(p!=NULL)p=p->next;        if(q!=NULL)q=q->next;    }    return head;}

1.对p、q、p->next、q->next进行判断:
if(((p!=NULL)?((p->next)!=NULL):0)||((q!=NULL)?((q->next)!=NULL):0)||(c==1))
这一语句的原来是用的if((p->next)!=NULL)||((q->next)!=NULL)||(c==1)),在运行过程中发现有错,当第一个链表为5,第二个链表为5时,运行到这一句由于c==1为真,程序继续运行,p=p->next,q=q->next,而当下一轮开始判断时,由于p和q此时都为null,便会造成错误,因此,要事先判断p、q是否为空,再判断其next是否为为空。

2.JAVA

/** * 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) {        ListNode lista = new ListNode(0);        ListNode listb = lista;        int c = 0;        while(l1!=null||l2!=null){            listb.val = listb.val+((l1!=null)?l1.val:0)+((l2!=null)?l2.val:0);            if(listb.val>9){                c=1;                listb.val-=10;            }else{                c=0;            }               if(((l1!=null)?(l1.next!=null):false)||((l2!=null)?(l2.next!=null):false)||c==1){                listb.next = new ListNode(0);                listb = listb.next;                listb.val = c;            }               if(l1!=null) l1 = l1.next;            if(l2!=null) l2 = l2.next;              }        return lista;//此时listb已经指向链表末端所以要返回lista    }}
原创粉丝点击