码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2016-03-15 20:30:29      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}//构造函数
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
       ListNode dummy(0);//为带头结点的链表
ListNode
* p = &dummy; int cn = 0;//表示进位 while(l1 || l2) { int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); cn = val / 10; val = val % 10;//表示当前位 p->next = new ListNode(val);//申请新结点用来储存val,并利用构造函数初始化 p = p->next;//形成链表 if(l1) { l1 = l1->next; } if(l2) { l2 = l2->next; } } if(cn != 0) { p->next = new ListNode(cn); p = p->next; }//判断最高位 return dummy.next; } };

以下是带结节点链表初始化操作

#include<iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}//构造函数
};

int main(){
    ListNode list(0),*rear(0),*head(0);
    rear=&list;
    int n;
    while(cin>>n){
        rear->next=new ListNode(n);
        rear=rear->next;
    }//以ctr+z结束 
    head=list.next;
    while(head){
        cout<<head->val<<" ";
        head=head->next;
    }
    return 0;
}

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/wqkant/p/5280887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!