1.算术从低位到高位,所以需要从后往前算,但是链表只能从前往后遍历。因此使用后进先出的栈,先将链表节点入栈,最后在同时出栈。
时间复杂度:O(n)
空间复杂度:O(n+m)栈空间加上新链表的空间
2.也可以先对两个链表进行反转,再从头节点开始进行计算。
时间复杂度:O(n)
空间复杂度:O(n)n为新链表的空间
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct stack{
int val;
struct stack* next;
}Node,Stack;
void InitStack(Stack* stack){
stack->val=0;
stack->next=NULL;
}
bool isEmpty(Stack* stack){
if(!stack->next)
return true;
return false;
}
void push(Stack* stack,int val){
Node* node=(Stack*)malloc(sizeof(Stack));
node->val=val;
node->next=stack->next;
stack->next=node;
}
int pop(Stack* stack){
if(isEmpty(stack))
return -1;
Node* head=stack->next;
int ret=head->val;
stack->next=head->next;
free(head);
return ret;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
//使用两个栈来存储l1和l2
Stack stack1,stack2;
InitStack(&stack1);
InitStack(&stack2);
while(l1){
push(&stack1,l1->val);
l1=l1->next;
}
while(l2){
push(&stack2,l2->val);
l2=l2->next;
}
struct ListNode* prehead=(struct ListNode*)malloc(sizeof(struct ListNode));
prehead->val=0;
prehead->next=NULL;
char carry=0;
while(!isEmpty(&stack1)||!isEmpty(&stack2)||carry){
char val1=pop(&stack1);
if(val1<0) val1=0;
char val2=pop(&stack2);
if(val2<0) val2=0;
char sum=val1+val2+carry;
char val=sum%10;
carry=sum/10;
struct ListNode* node=(struct ListNode*)malloc(sizeof(struct ListNode));
node->val=val;
node->next=prehead->next;
prehead->next=node;
}
l1=prehead->next;
free(prehead);
return l1;
}