c++链表操作
#include <stdio.h>
#include<iostream>
using namespace std;
class mystudent
{
public:
mystudent(int age):m_age(age),m_next(nullptr)
{
}
mystudent* insert_from_tail(mystudent*head)
{
if(!head)
{
cout<<"头节点为空:"<<endl;
return nullptr;
}
mystudent*tail = head;
cout<<"请输入节点:"<<endl;
int num = 0;
while(1)
{
cin>>num;
if(num<0)
{
break;
}
mystudent*tmp = new mystudent(num);
head->m_next = tmp;
head = head->m_next;
}
return tail;
}
mystudent *insert_from_head(mystudent*head)
{
if(!head)
{
return nullptr;
}
int num = 0;
mystudent*tail=head;
cout<<"请输入节点:"<<endl;
while(1)
{
cin>>num;
if(num<0)
{
break;
}
mystudent*tmp = new mystudent(num);
tmp->m_next = head->m_next;
head->m_next = tmp;
}
return tail;
}
void print_node(mystudent*head)
{
if(!head)
{
return;
}
while(head)
{
cout<<head->m_age<<"->";
head = head->m_next;
}
}
private:
int m_age = 0;
mystudent*m_next;
};
using namespace std;
int main()
{
mystudent*m = new mystudent(10);
mystudent*head =m->insert_from_head(m);
head->print_node(head);
cout<<endl;
return 0;
}
|