LeetCode-2.兩數相加

地址:https://leetcode-cn.com/problems/add-two-numbers/

思路:有關於鏈表指針的應用,算是複習了一遍吧

Code:

#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<map>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head=new ListNode(-1),*p=head;
        int x,pre=0;
        while(l1!=NULL||l2!=NULL){
        	x=0;
        	if(l1!=NULL){
        		x+=l1->val;
				l1=l1->next;
			}
        	if(l2!=NULL){
        		x+=l2->val;
        		l2=l2->next;
			}
			p=p->next=new ListNode((x+pre)%10);
			pre=(x+pre)/10;
		}
		if(pre){
			p=p->next=new ListNode(pre);
		}
        return head->next;
    }
};

void Print(ListNode* p){
	cout<<"Print  ";
	while(p!=NULL){
		cout<<p->val<<" ";
		p=p->next;
	}
	cout<<endl;
}

ListNode* Get(vector<int> iv,int n){
	ListNode *head=new ListNode(-1),*p=head;
	for(int i=0;i<n;++i)
		p=p->next=new ListNode(iv[i]);
	return head->next;
}

int main()
{
	int n,m,x;
	vector<int> iv1,iv2;
	cin>>n>>m;
	for(int i=0;i<n;++i)
	{
		cin>>x;
		iv1.push_back(x);
	}
	for(int i=0;i<m;++i)
	{
		cin>>x;
		iv2.push_back(x);
	}
	ListNode *p1,*p2;
	p1=Get(iv1,n);
	p2=Get(iv2,m);
	Print(p1);
	Print(p2);
	
	Solution So;
	ListNode *head;
	head=So.addTwoNumbers(p1,p2);
	Print(head);
	
	return 0;
}

 

發佈了325 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章