目录
1.单链表的基本操作
#include <iostream>
using namespace std;
typedef int Elemtype;
typedef struct LinkNode {
Elemtype data;
LinkNode *next;
} LinkNode, *LIST, *Node;
void Insert(Elemtype x, Node p)
{ //在结点p后插入指定数据x
Node q = new LinkNode;
q->data = x;
q->next = p->next;
p->next = q;
}
void Delete(Node p)
{ //删除p的下一个节点q
if (p->next != NULL) {
Node q = p->next;
p->next = q->next;
delete q; //删除结点q,释放内存
}
}
void CreatList(LIST &L)
{ //此函数创建带头结点的单链表, 通常也推荐使用带头结点的
//尾插法创建单链表, 待链接的结点node, L的尾结点last
Node node, last;
L = last = new LinkNode; //创建一个空的头结点
//此时L仅含一个结点, 故这个结点既是头结点也是尾结点
cout << "请输入单链表(以-1结束)" << endl;
while (true) {
node = new LinkNode;
last->next = node; //将当前结点链在L当前的尾部
cin >> node->data; //给刚链接上的结点赋予输入值
if (node->data == -1)
break; //若用户输入-1则完成创建单链表
last = node; //更新L尾结点,即当前结点成为L尾部
}
last->next = NULL; //置空尾结点, 使L尾部与多余结点断开
}
void PrintList(LIST &L)
{ //此函数输出带头结点的单链表
//将L的第一结点赋予p
Node p = L->next;
cout << "单链表为: ";
for (; p; p = p->next) {
cout << p->data << " ";
}
cout << endl;
}
2.单链表的进阶操作
2.1两个单链表的合并
LIST Merge(LIST &L1, LIST &L2)
{ //此算法来自《数据结构C语言》算法2.12
//已知单链表L1,L2递增排序, 需将1,L2归并为递增的L0
//L1,L2的待插入点node1,node2, L0的尾结点last0
Node node1 = L1->next, node2 = L2->next, last0;
LIST L0 = last0 = new LinkNode; //创建空结点last0并链在L0尾部, 此时last0也是L0第一结点
while (node1 && node2) {
if (node1->data <= node2->data) {
last0->next = node1;
last0 = node1; //更新L0尾结点, 即使L1插入的结点成为L尾部
node1 = node1->next; //更新待插入点
} else {
last0->next = node2;
last0 = node2;
node2 = node2->next;
}
}
last0->next = node1 ? node1 : node2;
return L0;
}
2.2复制一个单链表
LIST Copy(LIST &L1)
{ //node1为L1中待链接到L0的结点
Node node1 = L1->next, node0, last0;
LIST L0 = last0 = new LinkNode;
for (; node1; node1 = node1->next) {
last0->next = node1;
last0 = node1;
}
last0->next = NULL;
return L0;
}
2.3删除单链表中值为x的结点
int Delete(LIST &L, int x)
{
Node node = L;
for (int count = 1; node != NULL; count++) {
if (node->next->data == x) {
Node dele = node->next;
node->next = dele->next;
delete dele;
return count;
}
node = node->next;
}
return -1;
}
3.综合示例
int main()
{
//例1. 创建两单链表再合并
LIST L, L1, L2;
CreatList(L1);
CreatList(L2);
L = Merge(L1, L2);
PrintList(L);
//例2. 旧表preL复制给空白表newL
LIST newL, preL;
CreatList(preL);
newL = Copy(preL);
PrintList(newL);
//例3. 删除指定值为3的结点
LIST L1 = NULL;
CreatList(L1);
PrintList(L1);
cout << "删除位置: " << Delete(L1, 3) << endl;
PrintList(L1);
}