简单的链表练习。。。。。。
实现:myList.h
1 #pragma once 2 3 #include <iostream> 4 5 using namespace std; 6 7 typedef struct _Node 8 { 9 _Node* next; 10 int data; 11 }Node; 12 13 class myList 14 { 15 public: 16 //初始化 17 myList(); 18 //销毁链表 19 void Destroy(); 20 //获取链表长度 21 int getLength(); 22 //获取指定位置的元素 23 Node* getElement(int pos); 24 //插入元素 25 bool insertElement(Node* node, int pos); 26 bool insertElement(Node* node); 27 //删除指定位置元素 28 bool delElement(int pos); 29 //打印链表 30 void show(); 31 32 ~myList(); 33 private: 34 Node *head; 35 int length; 36 };
myList.cpp
1 #include "myList.h" 2 3 4 5 myList::myList() 6 { 7 head = new Node; 8 if (NULL != head) 9 { 10 head->next = NULL; 11 head->data = 0; 12 length = 0; 13 } 14 else 15 { 16 cout << "初始化失败" << endl; 17 } 18 } 19 20 void myList::Destroy() 21 { 22 if (NULL != head) 23 { 24 delete head; 25 head = NULL; 26 length = 0; 27 } 28 } 29 30 int myList::getLength() 31 { 32 return length; 33 } 34 35 Node * myList::getElement(int pos) 36 { 37 if (pos > length) 38 { 39 cout << "访问越界" << endl; 40 return NULL; 41 } 42 43 if (head->next != NULL) 44 { 45 Node* curNode = head->next; 46 for (int i = 0; i < pos; ++i) 47 curNode = curNode->next; 48 return curNode; 49 } 50 else 51 { 52 cout << "链表为空" << endl; 53 return NULL; 54 } 55 } 56 57 bool myList::insertElement(Node * node, int pos) 58 { 59 if (pos > length) 60 { 61 cout << "访问越界" << endl; 62 return false; 63 } 64 else if (pos == length) 65 { 66 Node *curNode = head->next; 67 while (curNode->next) 68 curNode = curNode->next; 69 curNode->next = node; 70 length += 1; 71 return true; 72 } 73 else 74 { 75 Node *curNode = head->next; 76 for (int i = 0; i < pos-1; ++i) 77 curNode = curNode->next; 78 79 node->next = curNode->next; 80 curNode->next = node; 81 length += 1; 82 return true; 83 } 84 } 85 86 87 bool myList::insertElement(Node * node) 88 { 89 if (length == 0) 90 head->next = node; 91 else 92 { 93 Node *curNode = head->next; 94 while (curNode->next) 95 curNode = curNode->next; 96 curNode->next = node; 97 } 98 length += 1; 99 return true; 100 } 101 102 bool myList::delElement(int pos) 103 { 104 if (pos > length) 105 { 106 cout << "访问越界" << endl; 107 return false; 108 } 109 else if (pos == length) 110 { 111 Node *curNode = head->next; 112 for (int i = 0; i < pos-1; ++i) 113 curNode = curNode->next; 114 delete curNode; 115 length--; 116 return true; 117 } 118 else 119 { 120 Node *curNode = head->next; 121 for (int i = 0; i < pos-1; ++i) 122 curNode = curNode->next; 123 Node* tmp = curNode->next; 124 curNode->next = curNode->next->next; 125 delete tmp; 126 length--; 127 return true; 128 } 129 } 130 131 void myList::show() 132 { 133 if (length > 0) 134 { 135 Node *curNode = head->next; 136 while (curNode) 137 { 138 cout << curNode->data << endl; 139 curNode = curNode->next; 140 } 141 } 142 else 143 cout << "空" << endl; 144 } 145 146 myList::~myList() 147 { 148 Destroy(); 149 }