2.2.1—单链表—Add Two Numbers

来源:互联网 发布:分镜头制作软件 编辑:程序博客网 时间:2024/05/20 16:33
描述
You are given two linked lists representing two non-negative numbers. e digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

#include<iostream>using namespace std;struct node{int data;node *next;};class mylist{node *head;public:mylist(){head = new node();head->data = 0;head->next = NULL;}void CreateList(int a[], int n);void Display(); friend void AddTwoNum(mylist &list1, mylist &list2,mylist &list);~mylist();};void mylist::CreateList(int a[], int n){if (n == 1){head->data = a[n - 1];return;}node *p = head;p->data = a[0];for (int i = 1; i < n; i++){node *q = new node();q->data = a[i];p->next = q;p = q;}p->next = NULL;}void mylist::Display(){node *p = head;while (p){cout << p->data << " ";p = p->next;}cout << endl;}void AddTwoNum(mylist &list1, mylist &list2,mylist &list){node *res = list.head;node *p = list1.head;node *q = list2.head;//===int count = 1;int flag = 0;while (p&&q){if (count == 1){res->data = (p->data + q->data)%10;flag = (p->data + q->data) / 10;p = p->next;q = q->next;count++;}else{node *temp = new node();temp->data = (p->data + q->data + flag) % 10;flag = (p->data + q->data + flag) / 10;res->next = temp;res = temp;p = p->next;q = q->next;}}//===while (p){node *temp = new node();temp->data = (p->data+ flag) % 10;flag = (p->data +flag) / 10;res->next = temp;res = temp;p = p->next;}//===while (q){node *temp = new node();temp->data = (q->data + flag) % 10;flag = (q->data + flag) / 10;res->next = temp;res = temp;q = q->next;}res->next = NULL;}mylist::~mylist(){node *p = head;while (head){head = p->next;delete p;p = head;}delete p;}int main(){//===const int n = 6;int a[n] = { 3, 9, 5, 7, 1, 4 };//代表417593mylist list1;list1.CreateList(a, n);list1.Display();//===const int m = 5;int b[n] = { 8, 5, 6, 9, 1 };//代表19658mylist list2;list2.CreateList(b, m);list2.Display();//===mylist list;AddTwoNum(list1, list2,list);list.Display();}