Exchange the position of the node pointed to by P and the next node

Exchange the position of the node pointed to by P and the next node

topic

Given that the first node of the linear list is pointed out by the list, please write an algorithm to exchange the position of the node pointed to by P and the next node (assuming that p points to not the last node in the linked list).

analysis

The algorithm is divided into two parts

  • First: when p refers to the first node of the linked list;
  • Second: When P refers to the middle node of the linked list;

Code

// 交换P所指结点与其下一个结点的位置
LinkList EXCHANGE(LinkList list,LinkList p){    
	LinkList q = list;    
	if (p==q)    {        
		list=list->link;       
		p->link=p->link->link;        
		list->link=p;    
	}else    {        
		while (q->link!=p)   {           
			q=q->link;        
		}        
		// 这里的顺序不能换,避免断链。        
		q->link=p->link;        
		p->link=p->link->link;        
		q->link->link=p;            
	}    
    return list ;    
}

Guess you like

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