[Data structure] The headless cyclic singly linked list turns the predecessor of P node into the successor node of P

Problem Description

Assuming that the circular singly linked list is not empty, and there is no head node and no head pointer, the pointer P points to a node in the linked list. Please design an algorithm to change the predecessor of the node pointed to by P to the successor of the node pointed to by P.

Solution

This problem can also be seen as exchanging the positions of the successor nodes of p and p and
finding three pointers

p
pp: the predecessor of
pppp: the predecessor of the predecessor of p

void exchangeNode(Node p) {
    
    
	// 如果只有一个或者两个节点直接退出 
	if (p->next->next == p) {
    
    
		return;
	} 
	Node ppp = p, pp = p->next;
	//  找到 pp,ppp 
	while (ppp->next->next != p) {
    
    
		ppp = ppp->next;
		pp = pp->next;
	}
	// 交换节点 
	pp->next = p->next;
	ppp->next = p;
	p->next = pp; 
} 

The node disconnection and connection sequence is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39906884/article/details/109807758