C++ 单链表
C++ 动态链表
头文件代码:
1 #include<iostream> 2 #include<string> 3 //动态创建链表 4 using namespace std; 5 class LNode { 6 private: 7 string StudentNum; 8 string Name; 9 int age; 10 LNode *next; 11 public: 12 LNode() {}//构造函数 13 ~LNode() {}//析构函数 14 void Init(LNode **L); 15 int GetLen(LNode *L);//得到链表长度 16 void InsertElem(LNode *L,int i,string sn,string nm,int age);//插入 17 void DeleteElem(LNode *L,int i);//删除 18 void show(LNode *L);//显示 19 void destory(LNode *L);//销毁 20 }; 21 void LNode::Init(LNode **L) 22 { 23 *L = new LNode(); 24 (*L)->next = NULL; 25 }//初始化令头指针内指向为空值,这样符合初始化定义,同时传入头指针的地址只是为了改变头指针的内容 26 int LNode::GetLen(LNode *L) 27 { 28 LNode *p = L;//则应该改成p=L->next 29 int num=0; 30 while (p != NULL) 31 { 32 p = p->next; 33 num++; 34 } 35 return num; 36 }//当只有头节点传入进去的时候,GetLen的值为1,错误 37 void LNode::InsertElem(LNode *L,int i,string sn,string nm,int age) 38 { 39 //判断插入的有效性 40 if (i<1 || i>GetLen(L) + 1) 41 { 42 cout << "无效插入\n"; 43 return; 44 } 45 LNode *p=NULL, *q=NULL, *s; 46 s = new LNode(); 47 s->StudentNum = sn; 48 s->Name = nm; 49 s->age = age; 50 51 q = L; 52 int pos = 0; 53 while (pos <i) 54 { 55 p = q; q = q->next; 56 pos++; 57 } 58 s->next = q; 59 p->next = s; 60 61 }//插入 在第i个结点之前插入 62 void LNode::DeleteElem(LNode *L, int i) 63 { 64 //判断删除的有效性 65 if (i < 1 || i > GetLen(L)) 66 { 67 cout << "删除无效\n"; 68 return; 69 } 70 LNode *p = NULL, *q = NULL; 71 q = L; 72 int pos = 0; 73 while (pos < i) 74 { 75 p = q; q = q->next; 76 pos++; 77 } 78 p->next = q->next; 79 delete q; 80 }//删除第i个节点 81 void LNode ::show(LNode *L) 82 { 83 LNode *p = L->next; 84 while (p != NULL) 85 { 86 cout << "*************************************" << endl; 87 cout << "学生学号:" << p->StudentNum << endl; 88 cout << "学生姓名:" << p->Name << endl; 89 cout << "学生年龄:" << p->age << endl; 90 cout << "*************************************" << endl; 91 p = p->next; 92 } 93 94 } 95 void LNode::destory(LNode *L) 96 { 97 LNode *p = NULL, *tem = NULL; 98 p = L; 99 while (p != NULL) 100 { 101 tem = p; 102 p = p->next; 103 delete tem; 104 } 105 }//销毁每一个节点
带头结点的单链表重点理解:
1.初始化传入的是头指针的地址,其他操作均传入头节点
2.插入删除 指针的变化
测试主函数
#include<iostream> #include<string> using namespace std; #include"标头.h" int main() { LNode *Lian = new LNode(); Lian->Init(&Lian); for (int i = 1; i < 3; i++) { string sn, nm; int age; cout << "请输入学生学号:" ; cin >> sn; cout << "请输入学生姓名:"; cin >> nm; cout << "请输入学生年龄:"; cin >> age; Lian->InsertElem(Lian, i, sn, nm, age); } Lian->show(Lian); Lian->DeleteElem(Lian, 1); Lian->show(Lian); Lian->destory(Lian); }
有待完善