용's
[LeetCode] Add Two Numbers 본문
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
이하, Accept된 내 코드
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
class Solution {
protected:
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* retListNode = NULL;
int Carry = 0;
int longerLength = getLongLength(l1, l2);
ListNode* cur1 = l1;
ListNode* cur2 = l2;
int c = 0;
for (int i = 0; i < longerLength; i++){
int addedDigitValue =0;
if (cur1 != NULL && cur2 != NULL){
addedDigitValue = SumWithCarry(cur1->val, cur2->val, c);
cur1 = cur1->next; //8
cur2 = cur2->next; //NULL
}
else if (cur1 == NULL){
addedDigitValue = SumWithCarry(0, cur2->val, c);
cur2 = cur2->next;
}
else if (cur2 == NULL){
addedDigitValue = SumWithCarry(cur1->val, 0, c);
cur1 = cur1->next;
}
else{
break;
}
appendValue(retListNode, addedDigitValue);
}
if (c == 1){
appendValue(retListNode, c);
}
return retListNode;
}
/*
* 두 리스트를 인자로, 더 길이가 긴 리스트의 길이값을 반환
*/
int getLongLength(ListNode* l1, ListNode* l2){
int l1Length = getListLength(l1);
int l2Length = getListLength(l2);
int retLength = (l1Length > l2Length ? l1Length : l2Length);
return retLength;
}
/*
* 리스트의 길이값을 반환
*/
int getListLength(ListNode* l){
int retValue = 0;
ListNode* cur = l;
if (cur == NULL){
return 0;
}
while (cur->next != NULL){
retValue++;
cur = cur->next;
}
retValue++;
return retValue;
}
/*
* 자리값 숫자와 Carry 값을 인자로 받아 더하고 Carry 값을 새로 설정
*/
int SumWithCarry(int a, int b, int &c){
int retValue = a + b + c;
if (retValue > 9){
retValue -= 10;
c = 1;
}
else{
c = 0;
}
return retValue;
}
/*
* 리스트의 가장 끝 자리에 값 하나 추가
*/
void appendValue(ListNode* &l, int value){
ListNode* cur = l;
ListNode* newNode = new ListNode(value);
if (cur == NULL){
l = newNode;
return;
}
while (cur->next!=NULL){
cur = cur->next;
}
cur->next = newNode;
return;
}
/*
* 리스트의 모든 값 출력
*/
void printAllListValues(ListNode* L){
ListNode* cur = L;
if (cur == NULL){
cout << "There is no any VALUE!!" << endl;
return;
}
while (cur->next!=NULL){
cout << cur->val << " ";
cur = cur->next;
}
cout << cur->val << endl;
return;
}
};
'Computer Science > Coding Tips' 카테고리의 다른 글
[C++] 순열 만들기 (0) | 2015.10.12 |
---|---|
[C++] 문자열 입력받기(char *), char* 길이 구하기 (0) | 2015.05.27 |
[C++] 배열 전체 한번에 초기화 (0) | 2015.05.26 |