哑结点即头结点之前的结点
主要是实战一下链表的使用
链表相关知识
反转链表方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum = 0, carry = 0, v1 = 0, v2 = 0;
ListNode *head = new ListNode(0);
ListNode *cur = head;
while (l1 != NULL || l2 != NULL)
{
v1 = (l1 != NULL) ? l1->val : 0;
v2 = (l2 != NULL) ? l2->val : 0;
sum = v1 + v2 + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur -> next;
if (l1 != NULL)l1 = l1->next;
if (l2 != NULL)l2 = l2->next;
}
if (carry != 0)
cur->next = new ListNode(carry);
return head->next;
}
};

被折叠的 条评论
为什么被折叠?



