摘要
刷下题来回忆下数据结构
这道题刚开始做的时候忽略了最高位进位1
还猜想这个题到底带不带头节点。。
题意
两数相加: leetcode.
给两个链表,两个链表的首节点指针,倒序求和
思路
维护首尾指针,维护一个进位
tips:看最后有没有最高位进位,若有则还需要链接上进位数
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* retHead = NULL;
struct ListNode* retTail = NULL;
//首尾节点指针
int carry_bit = 0;//记录进位
while(l1 || l2){
//当l1 和 l2 不有一个不空时执行
int v = carry_bit;
//非空的时候再加
if(l1) v += l1->val;
if(l2) v += l2->val;
//算是否有进位
if(v > 9){
v -= 10;
carry_bit = 1;
}
else
carry_bit = 0;
//生成一个节点
struct ListNode* temp = malloc(sizeof(struct ListNode));
temp -> val = v;
temp -> next = NULL;
//处理头指针
if(retHead == NULL){
retHead = temp;
}
//处理尾巴指针
if(retTail == NULL){
retTail = temp;
}
else{
retTail->next = temp;
retTail = temp;
}
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
//最高位有进位
if(carry_bit){
struct ListNode* temp = malloc(sizeof(struct ListNode));
temp -> val = carry_bit;
temp -> next = NULL;
retTail->next = temp;
retTail = temp;
}
return retHead;
}