文章目录
- 1. 插入
- 2. 类型转换说明
- 2. 代码实现
1. 插入
// 插入
void insert(LinkList* list, int pos, LinkNode* data)
{if (!list || !data)return;if (pos < 0 || pos > list->size)return;LinkNode* curNode = &(list->head);for (int i = 0; i < pos; ++i) {curNode = curNode->next;}// 插入新节点// cur insert nextdata->next = curNode->next;curNode->next = data;list->size++;
}
2. 类型转换说明
参考:有关企业链表中数据类型的强制转换
此处说明:
struct Person
{// 注意LinkNode的位置,放置在首位;// main中:insert(list, 0, (LinkNode*)&p1);// (LinkNode*)&p1取首地址,即LinkNode的地址;// 这样的话在insert中作为节点插入;LinkNode node;std::string name;int age;
};int main()
{LinkList* list = init();Person p1, p2, p3, p4, p5;p1.name = "11";p1.age = 11;p2.name = "22";p2.age = 22;p3.name = "33";p3.age = 33;p4.name = "44";p4.age = 44;p5.name = "55";p5.age = 55;insert(list, 0, (LinkNode*)&p1);insert(list, 0, (LinkNode*)&p2);insert(list, 0, (LinkNode*)&p3);insert(list, 0, (LinkNode*)&p4);insert(list, 0, (LinkNode*)&p5);LinkNode* curNode = list->head.next;while (curNode) {// (Person*)curNode:curNode的地址也即是Person的首地址LinkNodePerson* p = (Person*)curNode;std::cout << p->name << p->age << std::endl;curNode = curNode->next;}destroy(list);return 0;
}
2. 代码实现
#pragma oncestruct LinkNode
{LinkNode* next;
};// 链表节点
struct LinkList
{LinkNode head;int size = 0;
};// 初始化链表
LinkList* init()
{LinkList* list = new LinkList();list->head.next = nullptr;list->size = 0;return list;
}// 插入
void insert(LinkList* list, int pos, LinkNode* data)
{if (!list || !data)return;if (pos < 0 || pos > list->size)return;LinkNode* curNode = &(list->head);for (int i = 0; i < pos; ++i) {curNode = curNode->next;}// 插入新节点// cur insert nextdata->next = curNode->next;curNode->next = data;list->size++;
}int find(LinkList* list, LinkNode* node) { return 0; }void remove(LinkList* list, int pos) {}int size(LinkList* list)
{if (!list)return -1;return list->size;
}void destroy(LinkList* list)
{if (!list)return;list->size = 0;delete list;
}