/*
将整数分解到单向链表中,并逆序输出
*/
#include<iostream>
using namespace std;
struct Node;
typedef int dataType;
typedef struct Node *PtrNode;
typedef PtrNode List;
typedef PtrNode Position;
struct Node{
dataType data;
Position next;
};
class NumLink{
int num;//整数
List list;
public:
NumLink(int n):num(n){
list=(List)malloc(sizeof(Node));
};
void reverseList();
void getList();
void show();
};
int main(){
NumLink num(3426);
num.getList();
num.show();
num.reverseList();
num.show();
return 0;
}
//位数由低到高存储
void NumLink::getList(){
Position p,s;
int i=0;
p=list;
p->next=NULL;
int data=num;
while(data){
s=(List)malloc(sizeof(Node));
s->data=data%10;
data=data/10;
p->next=s;
p=s;
p->next=NULL;
i++;
}
}
//链表逆序
void NumLink::reverseList(){
if(list->next==NULL){
cout<<"链表不存在"<<endl;
}else{
Position p,q,t;
p=list->next;
q=list->next->next;
t=NULL;
while(q!=NULL){
t=q->next;
q->next=p;
p=q;
q=t;
}
list->next->next = NULL; /*设置链表尾*/
list->next = p; /*调整链表头*/
}
}
void NumLink::show(){
if(list==NULL){
cout<<"构建链表出错"<<endl;
}else{
Position p;
p=list->next;
while(p){
cout<<p->data;
p=p->next;
}
cout<<endl;
}
}