算法题11:链表相加
思路1:反转链表
反转两个链表,从链表头也就是低位开始计算,使用头插法建立结果链表。
代码
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre = NULL;
ListNode *cur = pHead;
while(cur!=NULL){
ListNode *cur_next = cur->next; //指向当前节点的下一个结点
cur->next = pre; //逆转链表
pre = cur; //向后进一步
cur = cur_next;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
//a,b为反转链表后的头
ListNode *a = ReverseList(head1);
ListNode *b = ReverseList(head2);
// return b;
ListNode *head = NULL; //新链表的头结点
int num = 0; //记录结点数和
bool carry = false; //是否有进位
while(a!=NULL || b!=NULL){
if(carry) num = 1;
else num = 0;
//加和
if(a!=NULL && b!=NULL){
num = a->val + b->val + num;
a = a->next;
b = b->next;
}
else if(a==NULL){
num = b->val + num;
b = b->next;
}
else{
num = a->val + num;
a = a->next;
}
ListNode *temp = new ListNode(0);
if(num>=10){ //算下一位的进位
carry = true;
temp->val = num - 10;
}
else{
carry = false;
temp->val = num;
}
//前插法链接高位结点
temp->next = head;
head = temp;
}
//最高位存在进位,需要在头部再加一个结点
if(carry){
ListNode *temp = new ListNode(1);
temp->next = head;
head = temp;
}
return head;
}
思路2:利用辅助栈
借助栈的先进后出特性达到反转链表的效果,分别将两个链表入栈,弹出栈顶元素进行计算。
代码
//1、借助辅助栈
if(head1==NULL){
return head2;
}
if(head2==NULL){
return head1;
}
stack<int> s1;
stack<int> s2;
ListNode *p1 = head1;
ListNode *p2 = head2;
//入栈
while(p1!=NULL){
s1.push(p1->val);
p1 = p1->next;
}
while(p2!=NULL){
s2.push(p2->val);
p2 = p2->next;
}
ListNode *head = NULL; //新链表的头结点
int carry = 0; //是否有进位
while(!s1.empty() || !s2.empty()){
int num = carry; //记录结点数和
if(!s1.empty()){
num += s1.top();
s1.pop();
}
if(!s2.empty()){
num += s2.top();
s2.pop();
}
// cout<<num<<endl;
carry = num/10; //求进位
ListNode *temp = new ListNode(num%10);
temp->next = head;
head = temp;
}
//如果最高位有进位,要在头部加一个结点
if(carry > 0){
ListNode *temp = new ListNode(carry);
temp->next = head;
head = temp;
}
return head;