144-rearranged linked list

The topic is as follows:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
rearrange it to become: L0→Ln→L1→Ln-1→L2→Ln-2→…

You can't just simply change the internal value of the node, but need to actually exchange the node.
Given a linked list 1->2->3->4, rearrange it to 1->4->2->3
Given a linked list 1->2->3->4->5, rearrange it to 1-> 5->2->4->3

Problem-solving ideas:
1. Find the middle node of the entire linked list, and the q pointer points to the middle node.
2. Reverse the second half of the linked list.
3. Combine the two disassembled linked lists.

void reorderList(ListNode *head)
{
    
    
	if (head == NULL)
	{
    
    
		return;
	}
	ListNode *p= head;
	ListNode *q= head;

	while (p->next != NULL && p->next->next != NULL)
	{
    
    
		p = p->next->next;
		q = q->next;
	}
	//此时的q就是指向中间结点 
	
	p= q->next;//p指向中间结点的下一个结点 
	q->next = NULL;//把前半段链表提取出来,整个链表拆成2部分 
	ListNode *s; 
	q= NULL; //当作前驱节点使用
	while (p != NULL)
	{
    
    
	    s = p->next;
		p->next = q;
		q = p;
		p = s;
	}
	p = q; //p链表反转完毕
	q = head;//q回到整条链表的头结点位置 
	while (p != NULL && q!= NULL)
	{
    
    
		s = q->next;
		q->next = p; //q下一个链接p
		q = s;
		s =p->next;
		p->next =q;
		p = s;
	}
}

The code demonstration diagram is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/LINZEYU666/article/details/112972253