Merge one-way circular linked lists

Merge one-way circular linked lists

topic

It is known that non-empty linked lists (a1, a2, a3, a4, a5,..., an) only use singly linked lists with tail pointers as storage structures (set tail pointers to rear). Please write an algorithm to transform the linear table into (A1,a2,a3,a4,…,an-1,an,an-1,…,a4,a3,a2,a1).Requirement
: The linear table after transformation is only used to set the tail pointer rear one-way Linked list, and there is only one circular list in the algorithm.

analysis

The idea, the result is a linear table about an symmetry.
Step 1: Let the pointer q traverse the linked list sequentially from rear->link.
Step 2: Record the first node of the linked list, if it is pointed to by the pointer r.
Step 3: Copy the node information pointed to by q, assuming that there is a point pointed to by p.
Step 4: Insert p behind the tail pointer rear.
Step 5: Cycle the third and fourth steps.
Step 6: Point rear to the position pointed by r to form a loop.

Example

Initial time: (a1,a2,a3,a4,a5,...,an)
After changing: (a1,a2,a3,a4,...,an-1,an,an-1,...,a4,a3,a2, a1)

Code

// 合并单向循环链表
LinkList MERGELIST(LinkList rear){    
	LinkList p,q,r,s;    
	q=rear->link;    
	p=(LinkList)malloc(sizeof(BNode));    
	p->data = q->data;  // 复制q所指的数据信息    
	r=p;  // 记录第一个元素的位置    
	p->link=rear->link; // 将第一个元素插入链表末尾    
	rear->link=p;    
	q=q->link;     // 指向第二个元素    
	while (q!=rear)    {        
		s = q->link;   // q所指的指针下移        
		p=(LinkList)malloc(sizeof(BNode));  // 申请空间        			         p->data=q->data;   // 复制q所指的数据信息        
		p->link=rear->link;  // 将p插入rear所指的后面        	  		         rear->link=p;        
		q=s;            // 获得下一个处理的结点   
	 }
         rear=r; // 将尾指针指向r的位置,尾指针。   
          return rear;    
  }

Guess you like

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