/***node
a linked list demoios
by atomanc++
***/app
#include <iostream>ui
using namespace std;this
#if 1
class nodelist{
public:
unsigned int uiNum;
nodelist* pNext;
//nodelist(unsigned int x = 0) {this->uiNum = x; this->pNext = NULL;} //init type 1: "this->" is necessary.
nodelist(unsigned int x = 0) : uiNum(x), pNext(NULL) {} //init type 2: prefered initialization way.
};
#elseatom
// struct is equal to class in most case
struct nodelist{
unsigned int uiNum;
nodelist* pNext;
nodelist(unsigned int x = 0) : uiNum(x), pNext(NULL) {}
};
#endifspa
nodelist* addlist(nodelist* pList1, nodelist* pList2)
{
nodelist* pHeadList = new nodelist(0);
cout << "step 1: " << pHeadList->uiNum << endl;
nodelist* pResultList = pHeadList;
cout << "step 2: " << pResultList->uiNum << endl;
unsigned int uiCarry = 0;
while (NULL != pList1 || NULL != pList2 || 0 != uiCarry)
{
cout << "step 3" << endl;
unsigned int uiSum = ((NULL != pList1) ? pList1->uiNum : 0) + ((NULL != pList2) ? pList2->uiNum : 0) + uiCarry;
uiCarry = uiSum / 10;c++11
pResultList->pNext = new nodelist(uiSum % 10);
pResultList = pResultList->pNext;input
if (NULL != pList1) pList1 = pList1->pNext;
if (NULL != pList2) pList2 = pList2->pNext;
}
nodelist *pt = pHeadList->pNext;
delete pHeadList;
return pt;
}
int main()
{
nodelist list1(7), list2;
list1.pNext = new nodelist(9);
list2.pNext = new nodelist(9);
nodelist *pResultList = addlist(&list1, &list2);
cout << endl;
cout << "list1.uiNum = " << list1.uiNum << endl;
cout << "list2.uiNum = " << list2.uiNum << endl;
cout << "Sum = ";
while (NULL != pResultList)
{
cout << pResultList->uiNum;
pResultList = pResultList->pNext;
}
cout << endl;
}
/*
Narrow input, deep learning. We can learn more from research a single and classical model deeply.
This is a linked list model. we can learn something from it.
1. C++ standard. C++ is not only a language, but also a standard.
2. C++ include C, in MOST case, "class" is equal to "struct". We can use class or struct to create a linked list.
3. initialization type: initialize them in construct function or initialize them by initialization list. The latter is preferred. For the first way, you should not discard to use "this->" which it's very important. If not, when "x" is named "uiNum" it will happen mistake without any compile warning/error.
g++ -std=c++11 -o print.o linkedlist.cpp
./print.o
g++ -std=c++11 -o print.o linkedlist.cpp -g
gdb print.o
l
b ***
r
n
s
q
*/