//单链表//
#include <iostream>
#include <stdlib.h>
using namespace std;
template<typename Type>
struct Node
{
Type data;
Node *next;
Node(Type d = Type()) :data(d), next(NULL){}
};
template<typename Type>
class List
{
public:
List()
{
first = NULL;
//不带头节点的的单向链表。
}
void Insert(int val)//后插
{
Node<Type> *s = new Node<Type>(val);
Node<Type> *p = first;
if (NULL == first)
{
first = s;
p = first;
}
else
{
while (p->next != NULL)p = p->next;
s->next = p->next;
p->next = s;
p = s;
}
}
void Deleate(int val)//删除节点。
{
Node<Type> *p = first;
Node<Type> *pr = NULL;
int flags = 0;
while (p != NULL)
{
while (p!=NULL && p->data == val)
{
if (p == first)flags = 1;
Node<Type> *m = p->next;
delete p;
p = NULL;
p = m;
}
if (flags == 1)
{
first = p;
flags = 0;
}
if (pr!=NULL)
{
pr->next = p;
}
pr = p;
if (p!=NULL)
p = p->next;
}
}
void Inser_val(int val)//按值插入。
{
Node<Type> *s = new Node<Type>(val);
Node<Type> *p = first;
Node<Type> *pr = NULL;
while (p != NULL && p->data < val)
{
pr = p;
p = p->next;
}
if (pr != NULL)
{
s->next = p;
pr->next = s;
}
else
{
s->next = first;
first = s;
}
}
void Sort()
{
if (first == NULL || first->next == NULL)return;
Node<Type> *p = first->next;
Node<Type> *m = NULL;
first->next = NULL;
while (p != NULL)
{
m = p->next;
p->next = NULL;
this->Inser_val(p->data);
delete p;
p = NULL;
p = m;
}
}
void L_F()//逆序
{
Node<Type> *p = first;
if (p == NULL || p->next == NULL)return;
Node<Type> *q = NULL;
while (p != NULL)
{
Node<Type> *m = p->next;
p->next = q;
q = p;
p = m;
}
first = q;
}
void Printf()
{
Node<Type> *p = first;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
private:
Node<Type> *first;
};
int main()
{
List<int> list;
int a[] = {9,8,7,4,432,5,4,432,4,4,4,5,10,2,3};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
list.Insert(a[i]);
list.Printf();
list.L_F();
list.Printf();
return 0;
}
数据结构:单链表
最新推荐文章于 2024-07-30 22:05:03 发布