链式列表的数字高位在前与低位在前
这篇博客主要讲了借助链表实现两个数字的相加。链表分别是高位数字在前和低位数字在前
- 高位在前
- 低位在前
高位在前
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
对于这个题目,我实现的时候记住了栈,首先便利这两个链表,将数字放入栈里,由于高位在前,所以使用栈的话,低位就在栈顶了,然后遍历栈,结果放入一个栈,这样就又将高位放到了栈顶,这时候将数字从栈里弹出建立链表,就实现了;这种做法虽然时间复杂度是O(n),但是空间复杂度也是O(n);比较好的方法应该是将链表反向,然后直接相加,但是我这样做的时候出现了一些状况,还没有将程序弄对,等以后做出来了再贴上代码吧。
下面贴上这道题的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
struct ListNode* ne = new struct ListNode(0);
int carry = 0<