LeetCode 2 Add Two Numbers(链表操作)

来源:互联网 发布:共赢网络图片 编辑:程序博客网 时间:2024/06/06 05:06

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题目大意:给出两个表示两个非负整数的非空链表,链表按照逆序排列(即第一个节点表示个位,第二个节点表示十位,以此类推),求两个链表的和。

解题思路:先让两个链表的对应节点相加,然后再处理进位。

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* ans = l1;    struct ListNode* last;    struct ListNode* now;    while(l1 && l2){        l1->val += l2->val;        last = l1;        l1 = l1->next;        l2 = l2->next;    }    if(l2) last->next = l2;    now = ans;    while(now){        if(now->val >= 10){            now->val -= 10;            if(now->next) now->next->val += 1;            else{                now->next = malloc(sizeof(struct ListNode));                now->next->next = NULL;                now->next->val = 1;            }        }        now = now->next;    }    return ans;}

0 0
原创粉丝点击