今天小编给大家分享一下关于数据结构中线性表的链式存储结构,这里只放代码,在重要的代码后附上解释,但是不进行具体某一项操作的详细算法分析。希望大家都能将这部分知识学好,这是后面学习的基础。
单链表的基本操作:
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}Lnode, *LinkList;
//对链表进行初始化
void int_LinkList(LinkList &head)
{
head = new Lnode; //创建一个头结点
if (head != NULL) //说明动态分配空间成功
{
head->next = NULL; //头结点指向的首结点为空
}
}
//输出利用头插法创建的这个单链表
void printf(LinkList head)
{
LinkList p = head->next;
while (p != NULL)
{
cout << p->data << '\t';
p = p->next;
}
cout << endl;
}
//尾插法创建一个单链表
void creaT_LinkList(LinkList head)
{
LinkList p, tail = head;
int i, n;
cout << "请输入创建的链表的长度是多少:" << endl;
cin >> n;
for (i = 1;i <= n;i++)
{
p = new Lnode;
cin >> p->data;
tail->next = p;
tail = p;
tail->next = NULL;
}
}
//查找第i个位置上的一个节点
LinkList geti_LinkList(LinkList head, int i)
{
cout << "返回的节点记作p" << endl;
LinkList p = head;
int j = 0;
if (i <= 0)
cout << "查找的位置不合法!";
while (p->next != NULL && j<i)
{
p = p->next;
j++;
}
if (j == i)
cout << "查找位置的值是:" << p->data << endl;
else cout << "查找失败!";
return p;
}
//在p结点之后再增加一个插入一个结点(后插)
void insert1_LinkList(LinkList &head, LinkList p)
{
LinkList s; //此处的p应该是什么?
ElemType x;
s = new Lnode;
cout << "请给插入的结点数据域赋值:" << endl;
cin >> x;
s->data = x;
s->next = p->next;
p->next = s;
cout << "输出p后插入结点的链表如下:";
printf(head);
cout << endl;
}
//在p之前插入一个新的结点
void insert2_LinkList(LinkList &head, LinkList p)
{
LinkList s;
ElemType x,t;
s = new Lnode;
cout << "请给插入的结点数据域赋值:" << endl;
cin >> x;
s->data = x;
s->next = p->next;
p->next = s;
t = s->data;
s->data = p->data;
p->data = t;
cout << "输出p前插入结点的链表如下:";
printf(head);
cout << endl;
}
//删除链表中q结点的后继结点
void delete1_LinkList(LinkList &head, LinkList q)
{
LinkList s;
s = q->next;
q->next = s->next;
delete(s);
cout << "输出删除q后继结点的该链表:" << endl;
printf(head);
cout << endl;
}
//删除链表中q结点
void delete2_LinkList(LinkList &head, LinkList q)
{
LinkList s;
ElemType t;
s = q->next;
q->next = s->next;
t = s->data;
s->data = q->data;
q->data = t;
delete(s);
cout << "输出删除q前驱结点的该链表:" << endl;
printf(head);
cout << endl;
}
//删除q结点的前驱结点
void delete3_LinkList(LinkList &head, LinkList q)
{
LinkList s = head;
while (s->next != q)
s = s->next;
s->next = q->next;
s->data = q->data;
delete(q);
cout << "输出删除q前驱结点的该链表:" << endl;
printf(head);
cout << endl;
}
int main()
{
LinkList head, p, q;
ElemType e;
int i;
int_LinkList(head);
creaT_LinkList(head);
printf(head);
cout << "请输入要查找的数据是:" << endl;
cin >> e;
q = select_LinkList(head, e);
cout << "请输入要查找的位置是:" << endl;
cin >> i;
p = geti_LinkList(head, i);
insert1_LinkList(head, p);
insert2_LinkList(head, p);
delete1_LinkList(head, q);
delete2_LinkList(head, q);
delete3_LinkList(head, q);
return 0;
}
若有不对的地方,欢迎指正