The Dream Of leozp

try my best

Leetcode: Add Two Numbers

/**
 * 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) {
		if (l1 == NULL){
			return l2;
		}
		if (l2 == NULL){
			return l1;
		}
		ListNode *ans = l1;
		int cur = 0;
		ListNode *p=l1;
		while (l1 && l2){
			int temp = l1->val + l2->val + cur;
			l1->val = temp % 10;
			cur = temp / 10;
			p = l1;
			 l2 = l2->next;
			 if (l1->next == NULL && l2!=NULL){
				 l1->next = new ListNode(0);
				 l1 = l1->next;
				 break;
				
			 }
			 l1 = l1->next;
		}
		if (l1 == NULL && l2 == NULL && cur){
			ListNode * ff = ans;
			while (ff->next != NULL){
				ff = ff->next;
			}
			ff->next = new ListNode(1);
		
		}

		else if (l2!=NULL){
		while (l2 != NULL){
			int temp = cur + l2->val;

			l1->val = temp % 10;
			cur = temp / 10;
			l2 = l2->next;
			p = l1;
		
			l1->next = new ListNode(0);
			l1 = l1->next;

		 }
    		 if (cur){
    		  l1->val = 1;
    	  }
		}
		else if (l1!=NULL)
	  while(l1 != NULL){
		
			int temp = cur  + l1->val;
			l1->val = temp % 10;
			cur = temp /= 10;
			p = l1;
		
			if (l1->next == NULL &&  cur){
				l1->next = new ListNode(cur);
				l1->next->val = cur;
				l1 = l1->next;
				break;

			}
			
				l1 = l1->next;

	  }
	//  cout << ans->val << " " << ans->next->val << endl;
	  //cout << "fuck" << p->val << endl;
      
	 if (p->next && p->next->val == 0){
		  p->next = NULL;
	  }
		return ans;
	}
};

阅读更多
版权声明:本文为博主原创文章,欢迎指教~ https://blog.csdn.net/u013712847/article/details/52386256
个人分类: leetcode
上一篇Leetcode: Two Sum
下一篇Leetcode: Longest Substring Without Repeating Characters
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭