【Data Structure and Algorithm】Double Linked List Delete Maximum Node

topic:

  Question: Use a double linked list storage structure, and write an algorithm for deleting the maximum value node


Main ideas:

  1. Create two pointers p and  used to traverse all elements of the linked list; used to point to the array of qthe current largest elementpq
  2. pEvery time you pass through a node, compare p.data  with and   q.data, if p.data  >   q.data, qpoint to the point of the current p.
  3. When p -> next = frist the traversal is completed, check qthe element pointed to at this time, so that it can be q -> prior -> next = q ->priorfollowed free (q).

Illustration:

Diagram of deleting the maximum value node in double linked list


the code

//求双链表表长
int DllLength(){
    
    
	int cnt = 0;
	int m = first;
	while(m -> next != first)
	{
    
    
		m = m -> next;
		cnt++;
	}
	return cnt;
}
//比较,若p.data 大于 q.data则将p赋值给q
void compare(int *p, int *q){
    
    
	if(p.data > q.data) 
	q = p;
}
//删除双链表最大值节点
void DeleteDllMax(Dll){
    
    
	//p、q初始都指向第一个首元节点
	int p = first -> next, q = first -> next;
	for(int i = 0; i < DllLength(); i++){
    
    
		//p每移动一次就要将p和q的data进行比较
		p = p->next;
		compare(p , q);
	}
	//遍历完毕后删除q(指向最大值)
	q -> prior -> next = q -> next;
	q -> next -> prior = q -> prior;
	free(q);
	return;
}


code image

Complete code image


conclusion

  Because it is an algorithm side dish, the methods and ideas provided may not be very good, please bear with me~ If you have any questions, please leave a message to discuss. If you think this article is helpful to you, can you give me a free like? The communication between us is my biggest motivation!

Guess you like

Origin blog.csdn.net/Zchengjisihan/article/details/130002495