版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/91395990
问题:
假定用链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序
排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例:
样例 1:
输入: 6->1->7 2->9->5 输出: 9->1->2
样例 2:
输入: 1->2->3 4->5->6 输出: 5->7->9
python:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: The first list.
@param l2: The second list.
@return: the sum list of l1 and l2.
"""
def addLists2(self, l1, l2):
# write your code here
if l1 == None:
return l2
if l2 == None:
return l1
result = ListNode(0)
curNode = result
A = []
B = []
resultList = []
while l1 != None:
A.append(l1.val)
l1 = l1.next
while l2 != None:
B.append(l2.val)
l2 = l2.next
maxLen = max(len(A), len(B))
flag = 0
for i in range(-1,-1*(maxLen+1), -1):
if i >= -1*len(A) and i >= -1*len(B):
temp = A[i] + B[i] + flag
elif i < -1*len(A):
temp = B[i] + flag
else:
temp = A[i] + flag
resultList.append(temp%10)
flag = temp//10
if flag == 1:
resultList.append(flag)
for j in range(-1, -1*(len(resultList)+1), -1):
curNode.next = ListNode(resultList[j])
curNode = curNode.next
return result.next
C++:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param l1: The first list.
* @param l2: The second list.
* @return: the sum list of l1 and l2.
*/
ListNode * addLists2(ListNode * l1, ListNode * l2) {
// write your code here
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
ListNode *result = new ListNode(0);
ListNode *curNode = result;
stack<int> A;
stack<int> B;
stack<int> resultStack;
while(l1 != NULL)
{
A.push(l1->val);
l1 = l1->next;
}
while(l2 != NULL)
{
B.push(l2->val);
l2 = l2->next;
}
int maxLen = max(A.size(), B.size());
int flag = 0;
for(int i = 0; i < maxLen; i++)
{
int temp = 0;
if(A.size() > 0 && B.size() > 0)
{
temp = A.top() + B.top() + flag;
A.pop();
B.pop();
}else if(A.size() == 0)
{
temp = B.top() + flag;
B.pop();
}else
{
temp = A.top() + flag;
A.pop();
}
resultStack.push(temp%10);
flag = temp/10;
}
if(flag == 1)
{
resultStack.push(flag);
}
int resultStackLen = resultStack.size();
for(int j = 0; j < resultStackLen; j++)
{
curNode->next = new ListNode(resultStack.top());
resultStack.pop();
curNode = curNode->next;
}
curNode->next = NULL;
return result->next;
}
};