1.
使用
int i = 1;
ListNode* ln;
ln->val = 1;
ln = ln-next;
错误,初始化的问题,细节不清楚
正确用法是
ListNode* ln = new ListNode(i);
2.
ListNode *ln = new ListNode('-1');
ListNode *head = ln;
这样写是要用head去改变ln,
因为单链表在next的过程中是无法回溯的。
初版
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* reverse(ListNode* head){
cout<<"h="<<head->val;
ListNode* fN = head;
ListNode* bN = NULL;
while(fN!=NULL){
ListNode *temp = fN ->next;//设一个临时节点为fN的下一位
fN -> next = bN;//前进后的fN的下一节点为前一个
bN = fN;//bn去到fn所在位置
if(temp==nullptr)break;
fN = temp;//fn去到临时节点
}
cout<<"reverse1="<<fN;
return fN;
}
ListNode* calculate(int* big,int* small,int loop,int loopMin){
int num = 0;
//ListNode *ln=nullptr;//要返回的链表
ListNode* ln = new ListNode(-1);
ListNode* head = ln;
for(int j = loop ; j>=0 ; j--){
cout<<"loop="<<loop<<endl;
cout<<"loopM="<<loopMin<<endl;
if(loopMin>=0){
int temp = big[j]+small[loopMin--]+num;
cout<<"big[j]"<<big[j]<<"small[j]"<<small[j]<<endl;
if(temp>=10){//小的那一组数没走完时
num = 1;
//head->val = temp%10;
head->next = new ListNode(temp%10);
cout<<"1="<<temp%10<<endl;
}else{
num = 0;
head->next = new ListNode(temp);
cout<<"2="<<temp<<endl;
}
}
else{//小的那一组数走完了
int temp = big[j] + num;
if(temp>=10){
num = 1;
head->next = new ListNode(temp%10);
cout<<"3="<<temp%10<<endl;
}else{
num = 0;
head->next = new ListNode(temp);
cout<<"4="<<temp<<endl;
}
}
head = head ->next;
}
if(num == 1){
head->next = new ListNode(1);
}
return ln;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
int arr[9999];
int arr1[9999];
int i = 0;
ListNode* h1;
ListNode* h2;
h1 = head1;
h2 = head2;
while(h1 != nullptr){
arr[i++] = h1 -> val;
cout<<"h1="<<h1->val<<endl;
h1 = h1->next;
}
int arrSize = i;
i = 0;
while(h2 != nullptr){
arr1[i++] = h2 -> val;
h2 = h2->next;
}
int arr1Size = i;
int loop = 0;
int loopMin = 0;
ListNode* ln;
if(arr1Size>arrSize){
loop = arr1Size-1;
loopMin = arrSize-1;
return reverse(calculate(arr1, arr, loop, loopMin)->next);
}else{
loop = arrSize-1;
loopMin = arr1Size-1;
return reverse(calculate(arr, arr1, loop, loopMin)->next);
}
//while(ln!=nullptr){
//cout<<"ln1="<<ln->val<<endl;
//ln=ln->next;
//}
}
};
所以用head来next,
最后返回ln。