代码实现:
//线性表的链式表示
#include<iostream>
using namespace std;
typedef int Elemtype;
//定义单链表节点类型
typedef struct LNode {
Elemtype data;
struct LNode* next;
}LNode,*Linklist;
//初始化单链表
int Init_Linklist(Linklist& L) {
L = new LNode;
if (L == NULL) {
cout << "Failed to Initialize the linklist:out of memory" << endl;
exit(-1);
}
else {
L->next = NULL;
cout << "succede to initialize! " << endl;
}
return 1;
}
//头插法建立单链表
Linklist Head_insert(Linklist& L) {
LNode* s;
Elemtype x;
L = new LNode;
L->next = NULL;
cin >> x;
while (x != 0000) {
s = new LNode;
s->data = x;
s->next = L->next;
L->next = s;
cin >> x;
}
return L;
}
//尾插法建立单链表
Linklist Tail_insert(Linklist& L) {
Elemtype x;
L = new LNode;
LNode* s, * r=L;
cin >> x;
while (x != 1127) {
s = new LNode;
s->data = x;
r->next = s;
r = s;
cin >> x;
}
r->next = NULL;
return L;
}
//按序号查找结点
LNode *GetElem_address(Linklist L, int i) {//在表L中查找第i个元素,并返回其结点
if (i < 1)
return NULL;
int j = 1;
LNode* p = L->next;
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
//按值查找结点
LNode* GetElem_value(Linklist L, Elemtype x) {
LNode* p = L->next;
while (p != NULL || p->data != x) {
p = p->next;
}
return p;
}
//插入结点操作
bool LNode_insert(Linklist& L, int i, Elemtype x) {//在链表L的第i个结点位置插入元素值为x的新节点
if (i < 1)
return false;
LNode* p,*s;
p=GetElem_address(L, i - 1);
s = new LNode;
s->data = x;
s->next = p->next;
p->next = s;
return true;
}
//删除结点操作
bool LNode_delete(Linklist& L, int i,Elemtype& e) {//删除单链表L中第i个结点,并用e返回结点元素值
if (i < 1)
return false;
LNode* p,*q;
p = GetElem_address(L, i - 1);
q = p->next;
e = q->data;
p->next = q->next;
free(q);
cout << "结点删除成功!" << endl;
return true;
}
//求表长操作
int Getlength(Linklist L) {
LNode* p = L->next;
int length=0;
while (p != NULL) {
p = p->next;
length++;
}
return length;
}
//输出单链表
void showlist(Linklist L) {
LNode* p = L->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
Linklist L,Q;
Elemtype e=0;
Init_Linklist(L);
Init_Linklist(Q);
cout << "请输入单链表L的元素:" << endl;
Tail_insert(L);
cout << "请输入单链表Q的元素:" << endl;
Tail_insert(Q);
LNode_insert(L, 4, 15);
cout << "操作完成后L的元素为:" << endl;
showlist(L);
cout << "更新完成后L的表长为:" << Getlength(L) << endl;
LNode_delete(Q, 5, e);
cout << "被删除的元素为:" << e << endl;
cout << "操作完成后Q的元素为:" << endl;
showlist(Q);
cout << "更新完成后Q的表长为:" << Getlength(Q) << endl;
return 0;
}
运行结果: