#include using namespace std; #define ERROR 0 #define OK 1 // 链表节点的结构体 struct LNode { int data; // 数据域 struct LNode* next; // 指针域 }; // 新建链表,确认链表的长度 void New_LinkList(struct LNode* L,int n) { int i; int v; struct LNode* p; // 新建单链表 L->next = NULL; for (int i = n; i > 0; i--) { p = (struct LNode*)malloc(sizeof(struct LNode)); cin >> v; p->data = v; p->next = L->next; L->next = p; } } // 获取链表中指定位置的数据元素 int GetElem_LinkList(struct LNode* L,int i, int *e) { struct LNode* p; p = L->next; int j = 1; while (p && j < i) { p = p->next; ++j; } if (!p || j > i) { return ERROR; } *e = p->data; return OK; } // 在链表中指定位置插入数据 int Isert_LinkList(struct LNode* L, int i, int* e) { struct LNode* p, * s; p = L; int j = 0; while (p && j < i - 1) { p = p->next; ++j; } if (!p || j > i - 1) { return ERROR; } s = (struct LNode*)malloc(sizeof(struct LNode)); s->data = *e; s->next = p->next; p->next = s; return OK; } // 删除链表中制定数据元素 int Delete_LinkList(struct LNode* L, int i, int* e) { struct LNode* p, * q; p = L; int j = 0; while (p->next && j < i - 1) { p = p->next; ++j; } if (!(p->next) || j > i - 1) { return ERROR; } q = p->next; p->next = q->next; *e = q->data; free(q); return OK; } // 显示链表元素的内容 int Print_LinkList(struct LNode* L, char* s) { struct LNode* p; //cout<< p = L->next; if (p == NULL) { cout << "该链表为空!" << endl; return ERROR; } while (p != NULL) { cout << p->data<<" "; p = p->next; } cout << endl; return OK; } int main() { // 创建并初始化链表 struct LNode L; cout << "请输入五个节点的数据" << endl; New_LinkList(&L, 5); Print_LinkList(&L, (char*)"初始化链表:"); int s, v; // 插入数据 cout << "请输入数据插入的位置和值:"; cin >> s >> v; Isert_LinkList(&L, s, &v); Print_LinkList(&L, (char*)"插入后的节点数:"); // 查询数据 cout << "请输入数据查询的位置:"; cin >> s ; GetElem_LinkList(&L, s, &v); cout << "第" << s << "个数据是:" << v << endl; // 删除出数据 cout << "请输入数据删除的位置:"; cin >> s; if (Delete_LinkList(&L,s,&v)) { cout << "数据删除成功,你所删除的数据是:" << v << endl; } else { cout << "数据删除失败!" << endl; } Print_LinkList(&L, (char*)"删除后的链表:"); return 0; }