lintcode-167-链表求和
生活随笔
收集整理的這篇文章主要介紹了
lintcode-167-链表求和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
167-鏈表求和
你有兩個用鏈表代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序,使得第一個數字位于鏈表的開頭。寫出一個函數將兩個整數相加,用鏈表形式返回和。
樣例
給出兩個鏈表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
標簽
鏈表 Cracking The Coding Interview 高精度
思路
遍歷 2 個鏈表(即從各位開始進行加法),新建節點保存 2 個節點與上一位的進位 carry 的和,并重置 carry
需要注意的是,若鏈表最高位之和大于 10 ,需要再新建最高位節點
code
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:/*** @param l1: the first list* @param l2: the second list* @return: the sum list of l1 and l2 */ListNode *addLists(ListNode *l1, ListNode *l2) {// write your code hereListNode *head = new ListNode(0);ListNode *temp = head;int carry = 0;while (l1!= NULL && l2 != NULL) {int sum = l1->val + l2->val + carry;ListNode *node = new ListNode(sum % 10);carry = (sum >= 10);temp->next = node;l1 = l1->next;l2 = l2->next;temp = temp->next;}while (l1 != NULL) {int sum = l1->val + carry;ListNode *node = new ListNode(sum % 10);carry = (sum >= 10);temp->next = node;l1 = l1->next;temp = temp->next;}while (l2 != NULL) {int sum = l2->val + carry;ListNode *node = new ListNode(sum % 10);carry = (sum >= 10);temp->next = node;l2 = l2->next;temp = temp->next;}if (l1 == NULL && l2 == NULL && carry == 1) {ListNode *node = new ListNode(carry);temp->next = node;}return head->next;} };轉載于:https://www.cnblogs.com/libaoquan/p/7276889.html
總結
以上是生活随笔為你收集整理的lintcode-167-链表求和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1、基本概念理解
- 下一篇: 谷歌火狐浏览器限制的端口