leetcode-2(兩數相加鏈表實現)

#include<iostream>
using namespace std;
struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
ListNode* greate(int num){
	ListNode *head;
	ListNode *p,*r;//r爲尾指針
	head = new ListNode(num%10);
	r=head;
	num/=10;
	while(num!=0){
		p = new ListNode(num%10);
		num /= 10;
		p->next=NULL;
		r->next=p;
		r=p;
	}
	return head;
}
void prin(ListNode* head){
	ListNode *p=head;
	while(p!=NULL){
		cout<<p->val<<endl;
		p=p->next;
	}
}
void insert(ListNode* head,int n){
	ListNode *sert,*nex,*p;
	sert=new ListNode(2);
	p=head;
	while(p->val!=n)
	p=p->next; //插入到n後面
	
	nex=p->next;
	p->next=sert;
	sert->next=nex;
}
void deleter(ListNode* head,int n){
	ListNode *out;
	ListNode *p;
	
	p=head;
	while(p->val!=n){
		out=p;
		p=p->next;
	}
	out->next=p->next;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *head,*p,*r;
    head=new ListNode(0);
    r=head;
    int add = 0;
    int carry = 0;//進位
    while(l1!=NULL&&l2!=NULL){
    	add = l1->val+l2->val;
    	add +=carry;
    	carry/=10;
    	if(add>=10){
    		carry = add/10;
    		add-=10;
    	}
    	p = new ListNode(add);
    	
		p->next=NULL;
		r->next=p;
		r=p;
		l1=l1->next;
		l2=l2->next;
    }
    if(l1){
    	while(l1){
	    	add = l1->val;
	    	if(carry){
	    		add+=carry;
	    		carry/=10;
	    		if(add>=10){
		    		carry = add/10;
		    		add-=10;
		    	}
	    	}
	    	p = new ListNode(add);
	    	
			p->next=NULL;
			r->next=p;
			r=p;
			l1=l1->next;
	    }
    }else if(l2){
    	while(l2){
	    	add = l2->val;
	    	if(carry){
	    		add+=carry;
	    		carry/=10;
	    		if(add>=10){
		    		carry = add/10;
		    		add-=10;
		    	}
	    	}
	    	p = new ListNode(add);
	    	
			p->next=NULL;
			r->next=p;
			r=p;
			l2=l2->next;
	    }
    }
    if(carry){
    	p = new ListNode(carry);
		p->next=NULL;
		r->next=p;
		r=p;
    }
    
    return head->next;
}
int main(){
	int num1,num2;
	// scanf("%d%d",&num1,&num2);
	num1=5;
	num2=5;
	ListNode *h1,*h2,*ans;
	h1=greate(num1);
	h2=greate(num2);
	ans = addTwoNumbers(h1,h2);
	prin(ans);
	// insert(h1,1);
	// prin(h1);
	// deleter(h1,0);
	// prin(h1);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章