链表,对比数组可以节省空间,由数据域与指针域构成一个数据块,操作方便。
1 单链表创建算法思路:
- 申明一节点p
- 初始化一空链表
- 头指针指向NULL,即建立一个带表头节点的单链表
- 循环查找要插入地方或删除
包括头插与尾插两种方式实现节点插入,c++模板方式构建结构体,简单实现插入与删除节点
#include<iostream>
using namespace std;
template <typename T>
struct Node {
T data;
Node<T>* next;
//Node() { next = NULL; }
};
template <typename T1, typename T2>
struct StaNode {
T1 data;
T2 cur;
};
typedef Node<int>* link_type0;
typedef Node<int> value_type0;
typedef StaNode<int, int>* link_type;
typedef StaNode<int, int> value_type;
//动态链表
void dyLink(link_type0 head)
{
link_type0 t;
head->next = NULL;
//头插节点
//for (int i = 0; i < 5; i++)
//{
// t = new value_type;
// //t = (link_type)malloc(sizeof(value_type));
// t->data = i + 1;
// t->next = head->next;
// head->next = t;
//}
//尾插节点
link_type0 p = new value_type0;
p = head;
for (int i = 0; i < 5; i++)
{
t = new value_type0;
t->data = i + 1;
t->next = NULL;
p->next = t;
p = p->next;
}
p = head;
for (int i = 0; i < 5; i++)
{
cout << p->data << endl;
p = p->next;
}
//删除节点
p = head;
while (p->next && p->next->data != 3)
{
p = p->next;
}
if (!p->next)
cout << -1 << endl;
p->next = p->next->next;
link_type0 p1 = new value_type0;
p1 = head->next;
while(p1)
{
cout << p1->data << endl;
p1 = p1->next;
}
//删除整个链表
p = head;
link_type0 q;
while (p)
{
q = p->next;
free(p);
p = q;
}
head->next = NULL;
p = NULL;
free(p);
free(p1);
}
int main()
{
link_type0 head0 = new value_type0;//动态
dyLink(head0);
system("pause");
}
2 循环链表
只是将单链表尾指针由NULL变为头指针地址。在单链表与循环链表判断上,前者判断p->next 不为空,后者判断p->next != head代表循环一圈。
3 双向链表
在单链表基础上,每个节点数据块添加前驱指针即可
template <typename T>
struct Node {
T data;
Node<T>* next;
Node<T>* prior;
};
节点s插入链表中
s->prior = p;
s->next = p->next;
p->next = s;
p->next->prior = s;
删除p所指节点
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
4 单链表翻转
将节点依次打断,重新连接
link_type0 reverseLink(link_type0 head)
{
link_type0 p, q, pr;
q = NULL;
p = head->next;
head->next = NULL;
while (p)
{
pr = p->next;
p->next = q;
q = p;
p = pr;
}
head->next = q;
cout << "翻转之后:" << endl;
link_type0 p1 = new value_type0;
p1 = head->next;
while (p1)
{
cout << p1->data << endl;
p1 = p1->next;
}
return head;
}