原题链接:https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
题目理解:给定两个链表,链表中每个节点表示十进制数的每一位,这样一个链表就能表示一个整数,目的是利用两个链表相加来获得其代表的整数的值。
根据观察可以发现最低位在链表的末端,但由于链表只能根据head以及next来获得他的下一位,所以要想从末尾开始进行运算,必须先获得两个链表的逆序,参考https://blog.csdn.net/qq_46126258/article/details/121023693可原地逆序。然后根据head进行正向计算即可,值得注意的是如果对应位相加=0则应该进1,若当前为最后一位没有办法进1,就应该新建一个节点。加和的第一位应该是整数的最后一位,所以加和新链表res应使用头插法建表,这样从head向下遍历得到的顺序为从高到低。
/**
* 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* ReverseList(ListNode* pHead){
ListNode *pre=nullptr;
ListNode *cur=pHead;
ListNode *nex=nullptr;
while(cur){
nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
//获得逆序链表H1、H2
ListNode *H1 =ReverseList(head1);
ListNode *H2 =ReverseList(head2);
//加和新链表res
ListNode *res =NULL;
int tmp,jinwei=0;
while(H1||H2){
int x1 = H1==nullptr? 0 : H1->val;
int x2 = H2==nullptr? 0 : H2->val;
tmp = x1 + x2 + jinwei;
jinwei = tmp / 10; //除数作为进位
ListNode *p = new ListNode(tmp%10); //将余数作为加和
//头插法
p->next=res;
res=p;
H1 = H1 == nullptr? nullptr: H1->next;
H2 = H2 == nullptr? nullptr: H2->next;
}
//如果最后一位有进位,则新建一个节点再插入
if (jinwei>0){
ListNode *p = new ListNode(jinwei);
p->next=res;
res=p;
}
return res;
}
};
注!!!
头插法:第一个插入的节点在链表尾端。不需要记录头结点的位置,head初始化为null,新节点p->next=head; head=p;
尾插法:第一个插入的节点在链表首端。需要记录头节点位置,H=head;
此后使用H来更新。H->next=p; H=H->next;