头插头删尾插尾删
在链表的头部和尾部分别进行对数据插入和删除
头插
void ListPushFront(List* pead, ListDatatype x) { assert(pead); List* newnode = BuyListNode(x); List* cur =pead->next; pead->next = newnode; newnode->prev = pead; newnode->next = cur; cur->prev = newnode; //ListInsert(pead->next, x);这是在pos位置前插入数据,这里可进行复用,后面会有实现 }
新结点的前指针指向前一个节点,后指针指向后一个节点,就进行了链接。
尾插
void ListPushBack(List* pead, ListDatatype x) { assert(pead); List* newnode = BuyListNode(x); List* cur = pead->prev; pead->prev = newnode; newnode->next = pead; cur->next = newnode; newnode->prev = cur; //ListInsert(pead, x);这是在pos位置前插入数据,这里可进行复用,后面会有实现 }
在尾部插入和头插同理,需要改变的只有相邻节点间的指针
头删
void ListPopFront(List* pead) { assert(pead); assert(pead->next !=pead); List* cur = pead->next; List* second = cur->next; free(cur); pead->next = second; second->prev = pead; }
删除首节点,然后使头部指针指向后一个节点
尾删
void ListPopBack(List* pead) { assert(pead); assert(pead->prev); List* cur = pead->prev; List* second = cur->prev; free(cur); second->next = pead; pead->prev = second; }
删除尾节点,然后使头部指针与尾节点前的节点链接
查找与指定位置的插入与删除
我们可以通过对链表的遍历,然后找到数据的位置,进行插入、删除、更改等操作
查找
List* ListFind(List* pead, ListDatatype x) { assert(pead); List* cur = pead->next; while (cur != pead) { if (cur->val == x) { return cur; } cur = cur->next; } return NULL; }
给定一个元素的数据,然后在链表中进行遍历,找到后返回元素地址
pos位置前插入
void ListInsert(List* pos, ListDatatype x) { assert(pos); List* cur = pos->prev; List* newnode = BuyListNode(x); newnode->prev = cur; cur->next = newnode; newnode->next = pos; pos->prev = newnode; }
删除pos位置结点
void ListErase(List* pos) { assert(pos); List* cur = pos->prev; List* second = pos->next; cur->next = second; second->prev = cur; free(pos); }
以上在pos位置进行的操作,只要我们有了地址,就可以进行操作,这些都可以对前面的头插头删尾插尾删进行复用。
链表销毁
当链表我们不再需要使用的时候,就需要将其进行销毁,因为这些空间都是在堆上进行开辟的
void ListDestroy(List* head) { assert(head); List* cur = head->next; while (cur != head) { List* tmp = cur; cur = cur->next; free(tmp); } free(head); }
结言:
今天内容就到这里啦,时间不知不觉就8月了,距离暑假的结束也已经步入了倒计时,不知道大家这段时间有没有沉下心来好好学习呢。送给大家一句话:今天你做别人不愿意做的事,明天你就可以做到别人做不到的事。坚持的人只有少数,你只要静下心来,该有的都有得到,我与诸君共勉。当然也十分希望大家动动小手指,给博主一键三连,大家的支持是我前行的最大动力。