链表反转+交叉链接

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/silence2015/article/details/99548197

给个链表1->2->3->4->5->6
把它变成1->6->2->5->3->4

先把后半段链表反转,然后交叉链接前后半段链表即可

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <stack>

using namespace std;

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x) :val(x),next(NULL) {};
};

ListNode* reverse(ListNode* root)
{
	ListNode* new_head = root, * node = root->next;
	while (node)
	{

		root->next = node->next;
		node->next = new_head;
		new_head = node;
		node = root->next;
	}
	return new_head;
}
/*
给个链表1->2->3->4->5->6
把它变成1->6->2->5->3->4

先把后半段链表反转,然后交叉链接前后半段链表即可
*/
ListNode* changeList(ListNode* root)
{
	int len = 0;
	ListNode* node = root, * past_head = NULL, * new_head = root, * p = root, * q, * p_next, * q_next;
	while (node)
	{
		len++;
		node = node->next;
	}
	node = root;
	int cnt=0;
	while (cnt<len/2-1)
	{
		node = node->next;
		cnt++;
	}
	
	past_head = reverse(node->next); //past_head 指向后半段链表
	node->next=NULL;  // 这儿要特别注意,一定要将前半段链表末位指向NULL,不然会死循环
	
	cnt = 0;
	q = past_head;
	while (q)
	{
		p_next = p->next;
		q_next = q->next;
		p->next = q;
		q->next = p_next;
		p = p_next;
		q = q_next;
	}
	
	return new_head;
}

int main()
{
	ListNode* p1 = new ListNode(3);
	ListNode* p2 = new ListNode(2);
	ListNode* p3 = new ListNode(1);
	ListNode* p4 = new ListNode(4);

	p1->next = p2;
	p2->next = p3;
	p3->next = p4;


	ListNode* res = changeList(p1);
	
	while (res)
	{
		cout << res->val<<" ";
		res = res->next;
	}
	
	system("pause");
}
展开阅读全文

没有更多推荐了,返回首页