(算法总结)单链表的中间段逆序(leetcode92)

链表的就地逆置我们讲解过了,接下来,关于单链表的中间段逆置,是一个稍有难度的问题。问题描述如下:

给定start和end,逆置从start到end的所有节点。

思路:这里需要定位逆置段开始节点,逆置段前驱结点,逆置段结束节点,以及逆置段结束节点后继。

定位好了之后,再对逆置段截断、做连接即可。

具体代码如下:

//	链表的中间段就地逆序
ListNode* inverse_between_list(ListNode* head, int start, int end) {
	int exchange_length = end - start + 1;
	ListNode* result = head;	//	最终返回的结果指针
	ListNode* pre_head = NULL;	//	逆置节点的前驱指针
	while (head && --start) {
		pre_head = head;
		head = head->next;
	}
	ListNode* modify_tail = head;
	ListNode* new_head = null;		//	将开始逆置段做截断
	while (head && exchange_length) {
		ListNode* tmp_ptr = head->next;
		head->next = new_head;
		new_head = head;
		head = tmp_ptr;
		exchange_length --;
	}
	modify_tail->next = head;	//	断层连接
	if (pre_head) {
		//	如果pre_head非空,即并非从头开始逆置,即start不等于1
		pre_head->next = new_head;
	} else {
		//	否则,就是从头开始逆置
		result = new_head;
	}
	return result;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值