链表问题

单链表反转

ListNode* reversenode(ListNode* p)
{
	if (p == NULL || p->next == NULL)	return p;
	ListNode* cur = p;
	ListNode* pre = NULL;
	ListNode* next = p->next;
	while (next)
	{
		cur->next = pre;
		pre = cur;
		cur = next;
		next = cur->next;		
	}
	cur->next = pre;
	return cur;
}

循环链表反转

void reverselist(ListNode* a)
{
	ListNode* head = a;
	ListNode* pre = a;
	ListNode* cur = a->next;
	ListNode* next = cur->next;
	while (cur != head)
	{
		
		cur->next = pre;
		pre = cur;
		cur = next;
		next = cur->next;
	}
	cur->next = pre;
}

反转链表中从m到n

ListNode *reversemn(ListNode* p, int m, int n)
{
	if (p == NULL || p->next == NULL || m == n)	return p;
	int t = n - m;
	ListNode* prehead = new ListNode(-1);
	prehead->next = p;
	ListNode* pre = prehead;
	while (m > 1)
	{
		pre = pre->next;
		m--;
	}
	//cur指向第m-1个节点
	ListNode* dump = pre->next;
	pre->next = NULL;
	ListNode* cur = dump;
	while (t)
	{
		cur = cur->next;
		t--;
	}
	ListNode* next = cur->next;
	cur->next = NULL;
	ListNode* newd=reversenode(dump);
	pre->next = newd;
	while (newd->next)
		newd = newd->next;
	newd->next = next;
	return prehead->next;
	
}

链表按照奇数或偶数拆分

void chaifen(ListNode* head) {
	if (head == NULL || head->next == NULL)	return;
	ListNode* p1 = head;
	ListNode* p2 = head->next;
	while ((p1&&p1->next) || (p2&&p2->next))
	{
		if (p1 != NULL && p1->next != NULL){
			p1->next = p1->next->next;
			p1 = p1->next;
		}
		if (p2 != NULL && p2->next != NULL)
		{
			p2->next = p2->next->next;
			p2 = p2->next;
		}
	}
}

143 重排链表

在这里插入图片描述

先找到中间节点,然后把后半段反转,然后按照流程变换链表即可。(已收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值