typedef void linklist;
struct linklistNode {
linklistNode* next;
};
struct linklistT {
linklistNode header;
int length;
};
linklist* createList() {
linklistT* list = new linklistT;
list->header.next = NULL;
list->length = 0;
return list;
}
void destoryList(linklist* list) {
if (list != NULL) {
delete list;
list = NULL;
}
}
void clearList(linklist* list) {
if (list != NULL) {
linklistT* ret = (linklistT*)list;
ret->length = 0;
ret->header.next = NULL;
}
}
int getLength(linklist* list){
if (list != NULL) {
linklistT *ret = (linklistT*)list;
return ret->length;
}
else {
return -1;
}
}
int insertNode(linklist* list, linklistNode* node, int pos) {
int ret = 0;
if (list == NULL || node == NULL || pos < 0) {
ret = -1;
return ret;
}
linklistT* listT = (linklistT*)list;
linklistNode* current = NULL;
current = &(listT->header);
for (int i = 0; i < pos && (current->next != NULL); i++) {
current = current->next;
}
//first
node->next = current->next;
//second
current->next = node;
listT->length++;
return 0;
}
linklistNode* deleteNode(linklist* list, int pos) {
if (list == NULL || pos < 0) {
return NULL;
}
linklistT* listT = (linklistT*)list;
linklistNode* current = &(listT->header);
for (int i = 0; i < pos && (current->next != NULL); i++) {
current = current->next;
}
linklistNode* item = current->next;
current->next = item->next;
//delete
listT->length--;
return item;
}
linklistNode* getNode(linklist* list,int pos) {
// = NULL;
if (list == NULL || pos < 0) {
return NULL;
}
linklistT* listT = (linklistT*)list;
linklistNode* current = &(listT->header);
for (int i = 0; i < pos && (current->next != NULL); i++) {
current = current->next;
}
listT->length++;
return current->next;
}
struct Teacher
{
linklistNode node;
int age;
char name[64];
};
int main() {
linklist* list = NULL;
Teacher t1, t2, t3, t4, t5;
t1.age = 31;
t2.age = 32;
t3.age = 33;
t4.age = 34;
t5.age = 35;
list = createList();
int len = getLength(list);
//cout << "list length: " << len << endl;
int ret = -1;
//len==0 类似头插法
ret = insertNode(list, (linklistNode*)(&t1), len);
//len = getLength(list); //类似尾插法
ret = insertNode(list, (linklistNode*)(&t2), len);
//len = getLength(list);
ret = insertNode(list, (linklistNode*)(&t3), len);
//len = getLength(list);
ret = insertNode(list, (linklistNode*)(&t4), len);
//len = getLength(list);
ret = insertNode(list, (linklistNode*)(&t5), len);
len = getLength(list);
for (int i = 0; i < len; i++) {
Teacher* t = (Teacher*)getNode(list, i);
cout << "index: " << i << " age: " << t->age << endl;
}
system("pause");
return 0;
}
单链表的实现
最新推荐文章于 2022-11-27 22:45:55 发布