从链表的指定位置读取参数
bool Link_GetElem(LinkList *&list, int i, int &e) {
if (!list) return false;
int index = 0;
LinkList *p;
p = list->next;
index = 1;
while (p && index < i) {
p = p->next;
index++;
}
if (!p || index > i) return false;
e = p->data;
return true;
}
从链表里存储的数据查找读取参数
bool Link_FindElem(LinkList *&list, int e, int &index) {
if (!list) {
index = 0;
return false;
}
LinkList *p;
p = list->next;
index = 1;
while (p && p->data != e) {
p = p->next;
index++;
}
if (!p) {
index = 0;
return false;
}
return true;
}
从链表删除单链表的参数
bool Link_Delete(LinkList *&list, int i) {
if (!list) return false;
int index = 0;
LinkList *p;
LinkList *q;
p = list;
while (p->next && index < i - 1) {
p = p->next;
index++;
}
if (!p->next || index > i - 1) return false;
q = p->next;
p->next = q->next;
delete q;
return true;
}
单链表销毁
void Link_Destroy(LinkList *&list) {
LinkList *p = list;
cout << "销毁链表" << endl;
while (p) {
list = list->next;
cout << "删除元素:" << p->data << endl;
delete p;
p = list;
}
}
完整代码实现
#include <iostream>
#include <Windows.h>
using namespace std;
typedef struct LinkNode {
int data;
LinkNode *next;
} LinkNode,
LinkList;
bool listInit(LinkList *&list) {
list = new LinkNode;
if (!list) return false;
list->next = NULL;
return true;
}
bool listAdd_Front(LinkList *&list, LinkNode *node) {
if (!list || !node) { return false; }
node->next = list->next;
list->next = node;
return true;
}
void listPrint(LinkList *&list) {
if (!list) return;
LinkNode *node;
cout << "链表的输出" << endl;
node = list->next;
while (node) {
cout << node->data << "\t";
node = node->next;
}
}
bool Link_GetElem(LinkList *&list, int i, int &e) {
if (!list) return false;
int index = 0;
LinkList *p;
p = list->next;
index = 1;
while (p && index < i) {
p = p->next;
index++;
}
if (!p || index > i) return false;
e = p->data;
return true;
}
bool Link_FindElem(LinkList *&list, int e, int &index) {
if (!list) {
index = 0;
return false;
}
LinkList *p;
p = list->next;
index = 1;
while (p && p->data != e) {
p = p->next;
index++;
}
if (!p) {
index = 0;
return false;
}
return true;
}
bool Link_Delete(LinkList *&list, int i) {
if (!list) return false;
int index = 0;
LinkList *p;
LinkList *q;
p = list;
while (p->next && index < i - 1) {
p = p->next;
index++;
}
if (!p->next || index > i - 1) return false;
q = p->next;
p->next = q->next;
delete q;
return true;
}
void Link_Destroy(LinkList *&list) {
LinkList *p = list;
cout << "销毁链表" << endl;
while (p) {
list = list->next;
cout << "删除元素:" << p->data << endl;
delete p;
p = list;
}
}
int main(void) {
LinkList *list = NULL;
LinkNode *node = NULL;
listInit(list);
int n;
cout << "前插法创建单链表" << endl;
cout << "请输入个数: ";
cin >> n;
while (n > 0) {
node = new LinkNode;
if (!node) return false;
for (int i = 0; i < n; i++) {
node->data = i + 1 * 10;
}
listAdd_Front(list, node);
n--;
}
listPrint(list);
Link_Destroy(list);
system("pause");
return 0;
}
|