여기에서는 연결 목록에 저장된 숫자로 1을 추가하는 방법을 살펴보겠습니다. 연결 목록에는 숫자의 각 자릿수가 저장됩니다. 숫자가 512이면 아래와 같이 저장됩니다 -
512 = (5)-->(1)-->(2)-->NULL
증분 함수에 목록을 제공하고 있습니다. 1을 추가한 후 다른 목록을 반환합니다. 여기서는 C++ STL 연결 목록을 사용하고 있습니다. 더 나은 아이디어를 내기 위한 알고리즘을 살펴보겠습니다.
알고리즘
증가 목록(l1)
Begin carry := 1 res := an empty list for each node n from l1, scan from last to first, do item := (l1.item + carry) mod 10 insert item at the beginning of res carry := (l1.item + carry) / 10 done if carry is not 0, then add carry at the beginning of res end if return res End
예
#include<iostream>
#include<list>
using namespace std;
list<int> incListNum(list<int> l1){
list<int>::reverse_iterator it1 = l1.rbegin();
list<int> result;
int carry = 1; //this 1 will be added
while(it1 != l1.rend()){
result.push_front((*it1 + carry) % 10);
carry = (*it1 + carry) / 10;
it1++;
}
if(carry != 0){
result.push_front(carry);
}
return result;
}
list<int> numToList(int n){
list<int> numList;
while(n != 0){
numList.push_front(n % 10);
n /= 10;
}
return numList;
}
void displayListNum(list<int> numList){
for(list<int>::iterator it = numList.begin(); it != numList.end();
it++){
cout<<*it;
}
cout << endl;
}
int main() {
int n1 = 9999;
list<int> n1_list = numToList(n1);
list<int> res = incListNum(n1_list);
cout << "The number: "; displayListNum(n1_list);
cout << "Result: "; displayListNum(res);
} 출력
The number: 9999 Result: 10000