LeetCode445

给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

 

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

 

这道题跟第二题类似,但是没有倒置链表,所以可以用栈去倒置。将各节点的元素依次压入栈,在计算的时候在pop,要注意的地方就是如果头节点的元素相加进位的情况,所以最后要有一个判断。

还有链表尾节点置为空,我坑了好几次。。。



#include<iostream>
#include<stack>
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)
	{
		stack<int> stackL1;
		stack<int> stackL2;
		while(l1){
			stackL1.push(l1->val);
			l1=l1->next;
		}
		while(l2){
			stackL2.push(l2->val);
			l2=l2->next;
		}

		ListNode* head=NULL;
		int sum=0;

		while(!stackL1.empty()||!stackL2.empty()){
			sum/=10;

			if(!stackL1.empty()){
				sum+=stackL1.top();
				stackL1.pop();
			}

			if(!stackL2.empty()){
				sum+=stackL2.top();
				stackL2.pop();
			}
			ListNode* node=new ListNode(sum%10);
			node->next=head;
			head=node;
		}
		//这个时判断链表都是空的了,但是还有进位的时候进行的运算
		if(sum>=10){
			ListNode* node=new ListNode(1);
			node->next=head;
			head=node;
		
	/*		head->next=node;	
			head=node;
			node->next=NULL;*/
		}

		return head;
	}



};

int main(){
 int n,m,j,k;
 ListNode* l1=(ListNode*)malloc(sizeof(ListNode)),*l2=(ListNode*)malloc(sizeof(ListNode)),*p=(ListNode*)malloc(sizeof(ListNode));
 ListNode* head1=l1;
 ListNode* head2=l2;
 cin>>n;
 for(int i=0;i<n;i++){
	 cin>>j;
	 ListNode *t=(ListNode*)malloc(sizeof(ListNode));
	 t->val=j;
	 t->next=NULL;
	 l1->next=t;
	 l1=t;
 }
 cin>>m;
 for(int i=0;i<m;i++){
	 cin>>k;
	 ListNode *t=(ListNode*)malloc(sizeof(ListNode));;
	 t->val=k;
	 t->next=NULL;
	 l2->next=t;
	 l2=t;
 }
 Solution solution;
 p=solution.addTwoNumbers(head1->next,head2->next);

 while(p){
	 cout<<p->val<<" ";
	 p=p->next;
 }
  system("pause");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值