In the previous blog, we used to talk about one-way linked list. So what is the difference between the linked list discussed today and the linked list discussed last time? The focus is on this "loop. With a loop, we can start to work from any linked list node, set the root user to any linked list node, and access data from any linked list node. This is the advantage of a loop.
So what are the differences between circular one-way linked lists during implementation?
1) print linked list data
void print_data(const LINK_NODE* pLinkNode){LINK_NODE* pIndex = NULL;if(NULL == pLinkNode)return;printf("%d\n", pLinkNode->data);pIndex = pLinkNode->next;while(pLinkNode != pIndex){printf("%d\n", pIndex->data);pIndex = pIndex ->next;}}
In the past, we found that the end of data printing is to judge whether the pointer is null. Here, it is changed because it is a circular linked list. Original condition (null! = Plinknode) is also modified here (plinknode! = Pindex ). The find function and count statistical function also need to be modified.
2) insert data
STATUS insert_data(LINK_NODE** ppLinkNode, int data){LINK_NODE* pNode;if(NULL == ppLinkNode)return FALSE;if(NULL == *ppLinkNode){pNode = create_link_node(data);assert(NULL != pNode);pNode->next = pNode;*ppLinkNode = pNode;return TRUE;}if(NULL != find_data(*ppLinkNode, data))return FALSE;pNode = create_link_node(data);assert(NULL != pNode);pNode->next = (*ppLinkNode)->next;(*ppLinkNode)->next = pNode;return TRUE;}
The insert function changes in two places:
A) if there are no nodes in the original linked list, the linked list node must point to itself.
B) if a linked list node exists, you only need to add a data entry to the current linked list node and modify the pointers in both directions.
3) delete data
STATUS delete_data(LINK_NODE** ppLinkNode, int data){LINK_NODE* pIndex = NULL;LINK_NODE* prev = NULL;if(NULL == ppLinkNode || NULL == *ppLinkNode)return FALSE;pIndex = find_data(*ppLinkNode, data);if(NULL == pIndex)return FALSE;if(pIndex == *ppLinkNode){if(pIndex == pIndex->next){*ppLinkNode = NULL;}else{prev = pIndex->next;while(pIndex != prev->next)prev = prev->next;prev->next = pIndex->next;*ppLinkNode = pIndex->next;}}else{prev = pIndex->next;while(pIndex != prev->next)prev = prev->next;prev->next = pIndex->next;}free(pIndex);return TRUE;}
Like adding data, deleting data also requires two changes:
A) if there is only one data left in the current linked list node, it must be set to null after deletion.
B) When deleting data, you first need the previous data of the current data. At this time, you can traverse the deleted data.
C) When deleting a table, you need to check whether the deleted data is the head node data of the linked list.