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 Subscribe to see which companies asked this question
题意:实际上就是342+465=807然后倒序输出。【一开始也没有看明白。】
参考别人的。一开始题意都没看明白。。。。。。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *l3 = (struct ListNode *)malloc(sizeof(struct ListNode)); l3->val=0; l3->next=NULL; //这边因为l3是一直往后遍历的,所以返回头的话要加个head指示一下。 struct ListNode* head = l3; l3->val=l1->val+l2->val; //while循环判断是否申请新的节点 l1=l1->next; l2=l2->next; while(l1||l2||l3->val>9){ l3->next=(struct ListNode *)malloc(sizeof(struct ListNode)); l3->next->val=0; l3->next->next=NULL; if(l1){ l3->next->val+=l1->val; l1=l1->next; } if(l2){ l3->next->val+=l2->val; l2=l2->next; } if(l3->val>9){ l3->next->val+=l3->val/10; l3->val=l3->val%10; } l3=l3->next; } return head; }
PS:主要是搞清楚有几种情况。9+8这种需要申请节点;12+9这种不等长的;
注意C语言链表的使用。。。
时间: 2024-10-02 04:34:50