最近复习真的是曾经学过的链表,所以做了一下leetcodeLinked List的题目,做的都是简单题,还非得挂这里,我也只能说权当纪录一下,何况人家雁过还留声呢,不想再像以前一样走过却啥也未曾留下——记忆有时候也不怎么靠谱。
题目:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Language C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *p, *h;
h = p;
int carry = 0; //int型进位符号carry
while(l1 || l2 || carry){
p->next = (struct ListNode *)malloc(sizeof(struct ListNode)); //新链表生成节点
p = p->next;
p->val = 0;
//加l1/l2元素值
if(l1){
p->val += l1->val;
l1 = l1->next;
}
if(l2){
p->val += l2->val;
l2 = l2->next;
}
// 调整进位
p->val += carry;
carry = p->val / 10;
p->val %= 10;
}
p->next = NULL;// It's very important! 新链表最后节点的next指向null
return h->next;
}