Delete other nodes with the same data field in the linked list

Delete other nodes with the same data field in the linked list

topic

Knowing that the pointer of the first node of the linear linked list is list, please write an algorithm to delete the nodes with the same data field value, that is, if there are multiple nodes in the linked list with the same data field value, only one node is retained , The remaining nodes are deleted from the linked list, so that the data field values ​​of all the nodes in the linked list are different.

analysis

Assuming that the pointer P points to a new data node, each time the pointer moves one bit, it must be checked whether it has appeared before, and the q pointer is checked from the initial position every time it is checked, so the time complexity is O(n^2).

E.g

The data of the original linked list: {1,2,2,4,2,6}
After deletion, the data is: { 1,2,4,6 }

Code 1

// 删除链表中数据域相同的其他结点
void DELETE3(LinkList list){    
	LinkList p,q,r;    
	p=list;    
	r=p;    
	p=p->link;    
	int flag=0;    
	while (p!=NULL){        
		q=list;        
		while (q!=p){           
			if (q->data!=p->data){              
				q=q->link;           
			}else{               
				flag=1;               
				break;          
	 		}// if       
	 	}// while       
	  	if (flag==1){          
	   		r->link=p->link;           
	   		free(p);           
	   		p=r->link;           
	   		flag=0;        
	  	}else{           
	    		r=p;            
	    		p=p->link;       
	      }// if 
	}// while
}

Code 1 is a bit cumbersome, please see the second one, just traverse and delete directly, without setting flags and so on.

Code 2

typedef struct node{    
	int data;    
	struct node *link;
}Node,*Linklist;
Linklist DELETE(Linklist list){    
	Linklist p,q ,r;    
	p=list;   
	while (p!=NULL) {        
		r=p;       
		q=p->link;       
		while(q!=NULL){           
			if (q->data==p->data){               
				r->link=q->link;               
				free(q);               
				q=r->link;          
			}else{               
				r=q;              
			 	q=q->link;           
			}       
		}//while       
	p=p->link;  
 }   // while
 return list;
}

Although the time complexity has not changed, the code is more understandable.

Guess you like

Origin blog.csdn.net/honeylife/article/details/98958366