链表
#include <map>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <time.h>
#include <vector>
#include <list>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//创建一个具有n个节点的链表,从键盘输入数据将其初始化,并返回链表的首节点指针
ListNode *createNode(int n)
{
ListNode *pHead(0), //首节点指针
*pRear(0), //尾节点指针
*pNew; //新节点指针
int i;
for (i = 0; i<n; i++)
{
pNew = new ListNode(0);
cin >> pNew->val;
if (0 == i)
{
pRear = pHead = pNew;
}
else
{
pRear->next = pNew;
}
pNew->next = NULL;
pRear = pNew;
}
return pHead;
}
//输出链表中的内容
void printNode(ListNode *pHead)
{
ListNode *pTemp = pHead;
while (pTemp != NULL)
{
cout << pTemp->val;
pTemp = pTemp->next;
}
cout << endl;
}
//查询链表中具有指定值的节点,并返回此节点指针
ListNode *searchNode(ListNode *pHead, int val)
{
ListNode *pDest = pHead;
while (pDest->next != NULL && pDest->val != val)
pDest = pDest->next;
if (pDest->val == val)
return pDest;
else
return NULL;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int a = 0, b = 0;
int num = 0;
ListNode *LL = l1;
while (LL != NULL)
{
a += LL->val*pow(10, num);
num++;
LL = LL->next;
}
LL = l2;
num = 0;
while (LL != NULL)
{
b += LL->val*pow(10, num);
num++;
LL = LL->next;
}
int c = a + b;
cout << c << endl;
ListNode *out, *save(0);
//调用前必须分配空间(指针赋值)
out = new ListNode(0);
out->val = c % 10;
save = out;
while ((c /= 10))
{
ListNode *front;
front = new ListNode(0);
front->val = c % 10;
save->next = front;
save = front;
}
save->next = NULL;
return out;
}
int main()
{
int i, j, N, M;
//m和n分别表示画布的宽度和高度,q表示画图操作的个数
cin >> N ;
ListNode *P = createNode(N);
printNode(P);
ListNode *q = createNode(N);
printNode(q);
ListNode * out = addTwoNumbers(P, q);
printNode(out);
cin >> N >> M;
return 0;
}