typedef struct LNode {
int data;
LNode *next;
}LNode,*LList; //LList(实质为LNode*)的无头结点表头
bool isEmptyLList(LList L) { //判断是否空表
if (L)
return false;
else
return true;
}
void showLList(LList L) { //遍历输出链表各结点值
if (isEmptyLList(L)) {
cout << "Empty!" << endl;
return;
}
LNode* showNode = L;
while (showNode) {
cout << showNode->data << " ";
showNode = showNode->next;
}
cout << endl;
return;
}
LNode* getLListTail(LList L) { //获取表尾结点
LNode *tailNode = L;
while (tailNode&&tailNode->next) {
tailNode = tailNode->next;
}
return tailNode;
}
int getLListLength(LList L){ //获取链表长度
int i = 0;
LNode* curNode = L;
if (!curNode) {
return i;
}
while (curNode&&curNode->next) {
curNode = curNode->next;
i++;
}
return i+1;
}
LNode* getLListLocate(LList L,int i) { //获取第i个结点
int len = getLListLength(L);
if (i > len || i < 1) {
return NULL; //非法值
}
LNode* locNode = L;
for (i; i>1; i--) {
locNode = locNode->next;
}
// while (i-->1) { locNode = locNode->next; }另一种循环方式
return locNode;
}
int searchLList(LList L,int e) { //搜寻存储数值为e的首个结点编号,未找到返回NULL
int i=1;
LNode *searchNode = L;
while (searchNode) {
if (searchNode->data == e) {
return i;
}
searchNode = searchNode->next;
i++;
}
return NULL;
}
int searchLList(LList L, LNode* node) { //搜寻结点n的编号,未找到返回NULL
int i = 1;
LNode *searchNode = L;
while (searchNode) {
if (searchNode == node) {
return i;
}
searchNode = searchNode->next;
i++;
}
return NULL;
}
void preAddLList(LList &L,int e) { //头插法增加一个结点
LNode *addNode = new LNode;
addNode->data = e;
if (isEmptyLList(L)) {
addNode->next = NULL;
L = addNode;
return;
}
addNode->next = L;
L = addNode;
return;
}
void preSetLList(LList &L) { //循环头插创建链表
int i;
while (cin >> i) {
if (i == '#')break;
preAddLList(L, (int)i);
}
return;
}
int preDelLList(LList &L) { //头删法减少一个结点
int e;
if (isEmptyLList(L)) {
cout << "Error: empty delete!" << endl;
return NULL;
}
LNode* delNode = L; //待删结点
LNode* headNode = L->next; //新的表头
e = delNode->data;
L = headNode;
delete delNode;
return e;
}
void tailAddLList(LList &L,int e) { //尾插增加一个结点
LNode *addNode = new LNode;
LNode *tailNode = getLListTail(L);
addNode->data = e;
addNode->next = NULL;
if (isEmptyLList(L)) {
L = addNode;
return;
}
tailNode->next = addNode;
return;
}
void tailSetLList(LList &L) { //循环尾插创建链表
int i;
while (cin>>i) {
if (i == '#')break;
tailAddLList(L,(int)i);
}
return;
}
int tailDelLList(LList &L) { //尾删减少一个结点
int e;
int len = getLListLength(L);
if (len < 1) {
cout << "Error: empty delete!" << endl;
return NULL;
}
if (len == 1) {
delete L;
L = NULL;
return NULL;
}
LNode* predelNode = getLListLocate(L, len - 1); //表尾前驱(新的表尾)
LNode* delNode = predelNode->next; //待删表尾
e = delNode->data;
predelNode->next = NULL;
delete delNode;
return e;
}
|