# 编程小白C++刷题–链表实现整数相加

## 题目–两数相加

#include<stdio.h>

#include<windows.h>

#include

using namespace std;

//链表的创建

typedef struct _ListNode {

int data;

struct _ListNode* next;


}listNode;

//链表的初始化

void InitList(listNode& list) {

list.next = NULL;


}

/*****************************/

bool OutPutList(listNode* list, int& num2);//输出链表存储的整数

bool DleteList(listNode* list);//释放链表的内存

/*****************************/

//添加链表节点

void addListNode(int num, listNode& list) {

int n, d;

listNode *l = &list;

while (num) {

n = num / 10;

d = num - n * 10;

listNode* m = (listNode*)malloc(sizeof(listNode));

m->data = d;

while (l->next != NULL)l = l->next;

m->next =l->next;

l->next = m;

num = n;

}


}

//链表相加

{
int num, num2;

if (!list1 || !list2)return NULL;

OutPutList(list1, num);

OutPutList(list2, num2);

num += num2;

listNode *list=new listNode;

InitList(*list);

return list;


}

//输出链表数据

bool OutPutList(listNode* list,int &num2) {

int x = 1,num=0;

if (list == NULL || list->next == NULL)return false;

list = list->next;

num2 = 0;

while (list) {

num= list->data;

num *= x;

num2 += num;

list = list->next;

x *= 10;

}

return true;


}

//释放链表空间

bool DleteList(listNode* list) {

if (list == NULL || list->next == NULL)return false;

list = list->next;

listNode* next = NULL;

while (list) {

next = list->next;

delete list;

list = next;

}

printf("链表空间释放成功！\n");

return true;


}

int main(void) {

listNode list1, list2;

int num,num2,num3;

//初始化两个相加的链表

InitList(list1);

InitList(list2);

//输入整数并加入链表，读取链表存入的正数，检查是否存入成功

printf("请输入第一个加数：");

scanf_s("%d", &num);

OutPutList(&list1,num2);

printf("list1的数据：%d\n",num2);

printf("请输入第二个加数：");

scanf_s("%d", &num);

OutPutList(&list2,num3);

printf("list2的数据：%d\n",num3);

//将两个链表中的整数相加并打印输出

OutPutList(sum, num);

printf("list1和list2的和为：%d\n", num);

//释放链表的空间

DleteList(&list1);

DleteList(&list2);

delete sum;

system("pause");

return 0;


}

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客