Cracking The Coding Interview2.4
2014-04-09 13:31
330 查看
删除前面的linklist,使用node来表示链表
// You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. // // EXAMPLE // //Input: (3 -> 1 -> 5), (5 -> 9 -> 2) // //Output: 8 -> 0 -> 8 #include <iostream> using namespace std; struct node { int data; node *next; }; void init(node *p,int a[], int size) { if (a==NULL || size<0) { return; } for (int i = 0; i < size; i++) { node *t = new node; t->data = a[i]; p->next = t; p = p->next; } p->next = NULL; } void print(node *head) { if (!head) { return; } node *p = head->next; while (p) { cout<<p->data<<" "; p = p->next; } cout<<endl; } node * plus(node *a, node *b) { node *pa = a->next; node *pb = b->next; node *pc = new node; node *pi = pc; int i = 0; int step = 0; while(pa!=NULL && pb!= NULL) { node *t = new node; int temp = pa->data + pb->data +step; step = 0; if (temp >=10) { temp %= 10; step = 1; } t->data =temp; pi->next = t; pi = t; pa = pa->next; pb = pb->next; } while(pa!= NULL) { node *t = new node; t->data = pa->data + step; step = 0; pi->next = t; pi = t; pa = pa->next; } while(pb != NULL) { node *t = new node; t->data = pb->data + step; step = 0; pi->next = t; pi = t; pb = pa->next; } if (step>0) { node *t = new node; t->data = step; pi->next = t; pi = t; } pi->next = NULL; return pc; } int main() { int a[6] = {1,4,5,9,7,8}; node *head = new node; init(head,a,6); print(head); int b[6] = {1,4,5,9,7,8}; node *h = new node; init(h,a,6); print(h); node * r = plus(head, h); print(r); return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第2章:链表——题目2
- 《Cracking the Coding Interview》——第5章:位操作——题目2
- Cracking the coding interview--Q12.7
- Cracking the coding interview--问题与解答
- Cracking the Coding Interview Q1.6
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目7
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
- Cracking the coding interview--问题与解答
- cracking the coding interview No1.6
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q18.1
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q1.3
- Cracking The Coding Interview 4.0_二叉树
- Cracking the coding interview--Q19.8
- Cracking the coding interview--问题与解答 目录
- Cracking the coding interview Q1.1
- Cracking the coding interview--Q3.5
- 《Cracking the Coding Interview》——第12章:测试——题目6