7-6 单链表的创建及遍历 (20分)
读入n值及n个整数,建立单链表并遍历输出。
输入格式:
读入n及n个整数。
输出格式:
输出n个整数,以空格分隔(最后一个数的后面没有空格)。
输入样例:
在这里给出一组输入。例如:
2
10 5
输出样例:
在这里给出相应的输出。例如:
10 5
#include<iostream>
#include<cstdio>
typedef struct MyNode* NodePoint;
struct MyNode
{
int data;
NodePoint link;
};
void CreateNode(int NodeData, NodePoint* PRear) {
NodePoint P;
P = (NodePoint)malloc(sizeof(struct MyNode));
P->data = NodeData;
P->link = NULL;
(*PRear)->link = P;
*(PRear) = P;
}
NodePoint ReadNode() {
int NodeNum, NodeData,PonitNum=0;
NodePoint P, Rear, Temp;
std::cin >> PonitNum;
P = (NodePoint)malloc(sizeof(struct MyNode));
P->link = NULL;
Rear = P;
for(int i=0;i<PonitNum;i++){
std::cin>>NodeData;
CreateNode(NodeData,&Rear);
}
Temp = P;
P = P->link;
free(Temp);
//std::cout << "Done" << "\n";
return P;
}
void NodeAdd1(NodePoint P1, NodePoint P2) {
if(P1==NULL&&P2==NULL){
std::cout<<"NULL"<<"\n";
}
NodePoint P, P0;
P = (NodePoint)malloc(sizeof(struct MyNode));
P0 = P;
while (P1 && P2) {
if (P1->data <= P2->data) {
P0->link = P1;
P0 = P1;
//std::cout << P0->data << "\n";
P1 = P1->link;
}
else {
P0->link = P2;
P0 = P2;
//std::cout << P0->data << "\n";
P2 = P2->link;
}
}
P0->link = P1 ? P1 : P2;
//P0->link = NULL;
P = P->link;
if(P) {
std::cout << P->data;
P = P->link;
}
while (P) {
std::cout << " " << P->data ;
P = P->link;
}
}
void NodeOut(NodePoint P) {
if(P==NULL){
std::cout<<"";
return;
}
int stats=0;
while (P) {
if(stats==0){
std::cout<<P->data;
stats=1;
} else{
std::cout<<" "<<P->data;
}
P=P->link;
}
}
int main() {
NodePoint P1, P2, P3;
P1 = ReadNode();
//P2 = ReadNode();
// NodeAdd1(P1, P2);
//NodeOut(P1);
NodeOut(P1);
}