链表(LinkList)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针。
单链表数据结构
struct Node
{
int _data ; // 数据
struct Node* _next; // 指向下一个节点的指针
}Node, *PLinkList;
//输出链表
void PrintList(PList head)
{
Node* begin = head;
while (begin != NULL)
{
cout<<begin->_data<<"->";
begin = begin->_next;
}
cout<<"NULL"<<endl;
}
Node* _CreateNode(DataType x)
{
Node* tmp = new Node;
tmp->_data = x;
tmp->_next = NULL;
return tmp;
}
//插入链表
void PushBack(PList& head, DataType x)
{
if(head == NULL)
{
head = _CreateNode(x);
}
else
{
Node* tail = head;
while(tail->_next != NULL)
{
tail = tail->_next;
}
tail->_next = _CreateNode(x);
}
}
//删除链表最后一个节点
void PopBack(PList& head)
{
if (NULL == head)
{
return;
}
else
{
Node* tail = head;
Node* p = head->_next;
while (NULL!=p->_next)
{
tail = p;
p = p->_next;
}
tail->_next = NULL;
}
}
//链表的头插
void PushFornt(PList& head, DataType x)
{
if(NULL == head)
{
head = _CreateNode(x);
}
else
{
Node *tail=_CreateNode(head->_data);
tail->_next=head->_next;
head->_next=tail;
head->_data=x;
}
}
//删除第一个链表节点
void PopFront(PList& head)
{
if (NULL == head)
{
return;
}
else
{
Node *tail=head->_next;
head->_data=head->_next->_data;
head->_next = head->_next->_next;
tail->_next = NULL;
}
}
//链表的逆序
void PrintTailToHead(PList head)
{
stack<Node*> s;
Node* begin = head;
while (begin != NULL)
{
s.push(begin);
begin = begin->_next;
}
while(!s.empty())
{
cout<<s.top()->_data<<"->";
s.pop();
}
cout<<endl;
}
//查找节点
Node* Find(PList head, DataType x)
{
Node* tail = head;
while (tail != NULL)
{
if (x == tail->_data)
{
return tail;
}
tail = tail->_next;
}
cout << "NULL" << endl;
return NULL;
}
//删除节点
void Erase(PList& head, Node* n)
{
Node* t = head;
Node* p = head->_next;
if (n == t)
{
PopFront(head);
}
else
{
while (p != NULL)
{
if (n == p)
{
t->_next = p->_next;
p->_next = NULL;
return;
}
t = t->_next;
p = p->_next;
}
}
}