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; }
分享题目:[LeetCode]2.AddTwoNumbers
文章分享:http://lswzjz.com/article/jjihci.html