標籤:ini turn 初始化 建立 display div next 鏈表 長度
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; 29 int num=0; 30 while (p != NULL) 31 { 32 p = p->next; 33 num++; 34 } 35 return num; 36 } 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 }//銷毀每一個節點View Code
帶頭結點的單鏈表重點理解:
1.初始化傳入的是頭指標的地址
2.插入刪除 指標的變化
C++ 動態鏈表