您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。