簡單的鏈表反轉 C++

#include
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class Mylist
{
private:
Node *head;
Node *curr;
int length;
public:
Mylist();
~Mylist();
void create(int value);
void display();
void reverse1();
};
Mylist::Mylist()
{
head=NULL;
curr=NULL;
length=0;
};
Mylist::~Mylist()
{
Node *pd=head;
Node *pf;
cout<<"Debug:析構函數:"<<endl;
while(pd!=NULL)
{
pf=pd->next;
delete(pd);
pd=pf;
}
};
void Mylist::create(int value)
{
Node *temp=new Node();
temp->data=value;
if(head==NULL)
{
head=temp;
curr=temp;
}
else
{
curr->next=temp;
curr=temp;
}
++length;
};
void Mylist::display()
{
cout<<"-----------------------------"<<endl;
cout<<"鏈表中的元素為:";
Node *node=head;
while(node!=NULL)
{
cout<<node->data<<' ';
node=node->next;
}
cout<<endl;
cout<<"鏈表中一共有:"<<length<<"個元素"<<endl;
cout<<"\n-----------------------------"<<endl;
};
void Mylist::reverse1()
{
Node *p=head;
Node *q;
Node *curr;
if(p==NULL)
return ;
else
{
q=p->next;
p->next=NULL;
}
while(q!=NULL)
{
curr=q->next;
q->next=p;
p=q;
q=curr;
}
head=p;
}
int main()
{
int n;
Mylist ilist;
cout<<"請輸入數據用以建製鏈表,輸入-1結束:"<<endl;
while(cin>>n&&n!=-1)
{
ilist.create(n);
}
ilist.display();
cout<<"鏈表反轉之後:"<<endl;
ilist.reverse1();
ilist.display();
return 0;


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章