//学完数据后第二次写链表,感觉比第一次要好一点点。
#include <iostream>
#include <cstdlib>
using namespace std;
typedef int DataType;
class Node //结点类
{
private:
DataType data;
Node *next;
public:
friend class LinkList;
Node(DataType d) //构造结点
{
data = d;
next = NULL;
}
Node() //构造头结点
{
next = NULL;
}
};
class LinkList
{
friend class Node;
private:
Node *head;
public:
LinkList();
~LinkList();
void Insert(DataType d); //插入
void Insert(int n, DataType d); //在n后面插入 d
void DeteleData(int n); //删除数据
void Sort(); //排序,大 -> 小
void Reversal(); //就地逆置
void Print(); //显示
};
LinkList::LinkList()
{
head = new Node();
}
void LinkList::Insert(DataType d) //插入
{
Node *p = new Node(d);
p->next = head ->next;
head ->next = p;
}
void LinkList::Insert(int n,DataType d)
{
Node *p = head;
while(n != 0)
{
p = p->next; //指向n结点
n--;
}
if(p == NULL)
{
cout<<"Wrong :"<<n<<"not have data"<<endl;
return ;
}
else
{
Node *q = new Node(d);
q ->next = p ->next; //插入P后面
p->next = q;
}
}
void LinkList::DeteleData(int n)
{
Node *p = head;
while( (n -1) != 0)
{
p = p->next; //P指向 n的前一结点
n--;
}
if(p == NULL)
{
cout<<"Wrong: There is no Data Delete"<<endl;
return ;
}
else
{ Node *q = p->next;
p->next = p->next ->next;
delete q;
}
}
void LinkList::Sort() //排序
{
Node *p, *q;
Node *qNext;
p = head;
q = p->next->next;
p->next->next = NULL; //断开第一个结点
qNext = q;
while(q != NULL)
{
p = head;
while (p->next->data > q ->data)
{
p = p->next; //P指向要插入数前一结点
if(p->next == NULL) break;
}
qNext = q->next;
q->next = p->next; //插入P后面
p->next = q;
q = qNext;
}
}
void LinkList::Reversal()
{
Node *p = head->next;
Node *pValue;
head ->next = NULL; //断开头结点
while(pValue != NULL)
{
pValue = p->next;
p->next = head->next; //不断往头结点后插入
head->next = p;
p = pValue;
}
}
void LinkList::Print() //显示
{
Node *p;
p = head->next;
if(p == NULL) //如果为空 返回
{
cout<<"Wrong : no data"<<endl;
return ;
}
while(p != NULL) //显示 ,直至为空
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
LinkList::~LinkList()
{
Node *p;
while(head != NULL)
{
p = head;
head = head->next; //删除所有结点
delete p;
}
}
void main()
{
LinkList link;
int data;
for (int i =0;i <10; i++)
{
data = rand()%15 +1; //产生随机数 1~15
link.Insert(data);
}
link.Insert(2,7);
link.DeteleData(6);
link.Reversal();
link.Print();
link.Sort();
link.Print();
}