这篇文章是在刷力扣的有关链表算法题有感而发
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int i = 0, j = 0,num = 0;
bool max10 = false, isFirst = true;
int temp = 0;
ListNode * head = new ListNode();
ListNode * ss = head;
while(l1 != NULL || l2 != NULL || max10){
i = 0; j = 0; temp = 0;
if(l1 != NULL){
i = l1->val;
l1 = l1->next;
}
if(l2 != NULL){
j = l2->val;
l2 = l2->next;
}
temp = i + j;
if(max10){
temp++;
max10 = false;
}
if( temp >= 10){
max10 = true;
temp -= 10;
}
if(isFirst){
head->val = temp;
isFirst = false;
}else{
ListNode * test = new ListNode(temp);
ss->next = test;
ss = ss->next;
}
}
return head;
}
};
如代码所示
ListNode * head = new ListNode(); //创建链表第一个结点(头节点)
ListNode * ss = head;//通过一个临时的链表节点指向头节点
ListNode * test = new ListNode(temp);
ss->next = test;
ss = ss->next;
后续对这个单向链表的操作都通过这个临时的头节点去操作,然后在函数返回的时候返回head(初始头节点)的方式从而达到返回链表头的效果,有感而发,有错误或者更加方便的方法敬请大家指出!