您好,登录后才能下订单哦!
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
根据给定的两个非负数组成的链表,对链表相应位值相加后组成一个新的链表,并返回。若相加和大于等于10,则该节点值为减10后的差,并向后一节点进一。
解题:
1)若传入两链表为空,则返回空链表;若链表l1为空,则直接返回链表l2即可;若链表l2位空,则直接返回链表l1即可
2)若两链表都不为空,则同时进行递增,直到有一个链表为空为止。
3)若一个链表为空,另一链表不为空,则递增不为空链表,直到为空。
4)最后检查最后一个节点是否有进位,若有,则再新增相应节点。否则,返回链表。
说明:
1)flag定义为进位值,若和大于等于10,则flag置1,否则flag置0.
2)head指向头节点,last指向尾节点。
3)新增节点时,先将last节点的next指向新增节点。再把新增节点赋值给last.
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { if ( l1 == NULL && l2 == NULL ) { return NULL; } if ( l1 == NULL ) { return l2; } if ( l2 == NULL ) { return l1; } int flag = 0; struct ListNode *head = NULL; struct ListNode *last = head; while ( l1 != NULL && l2 != NULL ) { int val = 0; struct ListNode *node = NULL; node = (struct ListNode *)malloc(sizeof(struct ListNode *)); if ( node == NULL ) { return head; } val = l1->val + l2->val + flag; if ( val >= 10 ) { val -= 10; flag = 1; } else { flag = 0; } node->val = val; node->next = NULL; if ( head == NULL ) { head = node; last = head; } else { last->next = node; last = node; } l1 = l1->next; l2 = l2->next; } while ( l1 == NULL && l2 != NULL ) { int val = 0; struct ListNode *node = NULL; node = (struct ListNode *)malloc(sizeof(struct ListNode *)); if ( node == NULL ) { return head; } val = l2->val + flag; if ( val >= 10 ) { val -= 10; flag = 1; } else { flag = 0; } node->val = val; node->next = NULL; last->next = node; last = node; l2 = l2->next; } while ( l1 != NULL && l2 == NULL ) { int val = 0; struct ListNode *node = NULL; node = (struct ListNode *)malloc(sizeof(struct ListNode *)); if ( node == NULL ) { return head; } val = l1->val + flag; if ( val >= 10 ) { val -= 10; flag = 1; } else { flag = 0; } node->val = val; node->next = NULL; last->next = node; last = node; l1 = l1->next; } if ( l1 == NULL && l2 == NULL && flag == 1 ) { struct ListNode *node = NULL; node = (struct ListNode *)malloc(sizeof(struct ListNode *)); if ( node == NULL ) { return head; } node->val = 1; node->next = NULL; last->next = node; last = node; } return head; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。