1. 问题描述:
用单链表表示十进制整数,求两个正整数的和。
例如:
输入:1234 34
输出:1268
注意,单项链表的方向从前向后,不允许使用其他数据结构。
图1. 样例
2. 代码实现:
#include <iostream>
#include <vector>
using namespace std;
typedef struct Node{
int value;
Node* next;
}Node;
void printList(Node* head){
if(head==NULL){
cout << "该链表为空链表!" <<endl;
return;
}
Node* p = head;
if(p!=NULL){
cout << p->value << ' ';
p = p->next;
}
}
Node* buildList(){
Node* head = new Node; // creat a head node.
Node* s = head;
cout << "Note that: link is builded done if -1 is input!" << endl;
while(1){
int number;
cin >> number;
if(number==-1)
break;
else{
Node* pNode = new Node; //creat a new node.
pNode->value = number;
s->next = pNode;
s = pNode;
}
}
head = head->next;
s->next = NULL;
return head;
}
int main(){
Node* Link1 = buildList();
Node* Link2 = buildList();
printList(Link1);
printList(Link2);
return 0;
}
网友评论