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
- LeetCode 2 Add Two Numbers(链表操作)
- [LeetCode-2] Add Two Numbers(链表数据之和)
- Add Two Numbers Leetcode 链表相加
- Leetcode Add two numbers链表相加
- 【LeetCode】链表相加 Add Two Numbers
- LeetCode(2)Add Two Numbers
- leetcode(2)add two numbers
- Add Two Numbers (leetcode 2)
- Leetcode问题-2(Add Two Numbers)
- Leetcode日记(2)---Add two numbers
- LeetCode(2)Add Two Numbers
- LeetCode(2) Add Two Numbers
- 【leetcode 2】 Add Two Numbers(C++)
- LeetCode (2)Add Two Numbers
- LeetCode(2)--Add Two Numbers
- LeetCode | Add Two Numbers(两个链表相加)
- Leetcode 2. Add Two Numbers(链表求和)
- LeetCode 2 - Add Two Numbers
- C# 动画播放控件 改进
- 二叉树做题总结
- Android 创建一个新的Activity
- 子树
- substr函数用法详解
- LeetCode 2 Add Two Numbers(链表操作)
- 【LeetCode with Python】 Generate Parentheses .
- JS 正则表达式RegExp(上)
- gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable
- java泛型中<?>和<T>有什么区别?
- 个人学习历程之菜鸟初体验mybatis高级映射一对一查询
- Java使用POI读取Excel文件
- 101. Symmetric Tree
- static相关用法