在这里由于两数相加用到的链表的成员函数比较少,没有单独实现链表的头文件和源文件。
单链表节点定义的头文件
#ifndef NODE_H
#define NODE_H
class Node
{
public:
Node(int data = 0);
int m_iVal;
Node* next;
void printNode();
void NodeTraverse();
bool NodeInsertTail(Node* pNode);
};
#endif
单链表节点成员函数实现的源文件
#include "pch.h"
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(int data)
{
m_iVal = data;
}
void Node::printNode()
{
cout << m_iVal << endl;
}
void Node::NodeTraverse()
{
Node* currentNode = this;
while (currentNode->next != nullptr)
{
currentNode = currentNode->next;
currentNode->printNode();
}
}
bool Node::NodeInsertTail(Node* pNode)
{
Node* currentNode = this;
while (currentNode->next != nullptr)
{
currentNode = currentNode->next;
}
Node* newNode = new Node;
if (newNode == nullptr)
{
return false;
}
newNode->m_iVal = pNode->m_iVal;
newNode->next = nullptr;
currentNode->next = newNode;
return true;
}
// Add_Two_Num.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include "Node.h"
using namespace std;
Node* addTwoNumbers(Node* node1, Node* node2)
{
Node* p1 = node1;
Node* p2 = node2;
Node* nodeHead = new Node(-1);
Node* cur = nodeHead;
int carried = 0;
while (p1 || p2)
{
//在两个单独链表的相同位置节点上进行整除取余的操作,
int a = p1 ? p1->m_iVal : 0;
int b = p2 ? p2->m_iVal : 0;
cur->next = new Node((a + b + carried) % 10);
carried = (a + b + carried) / 10;
//cur指向新生成的一个节点,
cur = cur->next;
// 对两个单独链表分别读取当前节点所指向的下一个相同位置的节点
p1 = p1 ? p1->next : nullptr;
p2 = p2 ? p2->next : nullptr;
}
cur->next = carried ? new Node(1) : nullptr;
Node* ret = nodeHead->next;
delete nodeHead;
nodeHead = nullptr;
return ret;
}
int main()
{
Node node1;
node1.m_iVal = 2;
Node node2;
node2.m_iVal = 4;
Node node3;
node3.m_iVal = 3;
Node node4;
node4.m_iVal = 5;
Node node5;
node5.m_iVal = 6;
Node node6;
node6.m_iVal = 4;
Node* headNode1 = new Node(0);
Node* headNode2 = new Node(0);
Node* headNode3 = new Node(0);
headNode1->NodeInsertTail(&node1);
headNode1->NodeInsertTail(&node2);
headNode1->NodeInsertTail(&node3);
headNode1->NodeTraverse();
headNode2->NodeInsertTail(&node4);
headNode2->NodeInsertTail(&node5);
headNode2->NodeInsertTail(&node6);
headNode2->NodeTraverse();
headNode3 = addTwoNumbers(headNode1, headNode2);
headNode3->NodeTraverse();
delete headNode1;
headNode1 = nullptr;
delete headNode2;
headNode2 = nullptr;
delete headNode3;
headNode3 = nullptr;
std::cout << "Hello World!\n";
}