链表反转以及指定区间反转

题目

(1)链表反转
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

数据范围: 0≤n≤10000≤n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。

如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
在这里插入图片描述
(2)指定链表区间反转
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1→2→3→4→5→NULL1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1→4→3→2→5→NULL1→4→3→2→5→NULL.

数据范围: 链表长度 0<size≤10000<size≤1000,0<m≤n≤size0<m≤n≤size,链表中每个节点的值满足 ∣val∣≤1000∣val∣≤1000
要求:时间复杂度 O(n)O(n) ,空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)
参考内容:https://blog.csdn.net/m0_61875824/article/details/131999097

代码

#include <iostream>
#include <vector>
using namespace std;

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x):val(x),next(nullptr){}
};
ListNode* reverseList(ListNode* list_head) {
	if (list_head == nullptr || list_head->next == nullptr) {
		return list_head;
	}
	ListNode* prev = nullptr;
	ListNode* curr = list_head;
	while (curr != nullptr) {
		ListNode* next_node = curr->next;
		curr->next = prev;//改变指针的指向
		prev = curr;//往后移动
		curr = next_node;
	}
	return prev;
}
ListNode* ReverseBetween(ListNode* head_node, int m, int n) {
	ListNode* dummy = new ListNode(-1);
	dummy->next = head_node;
	ListNode* pre = dummy;//反转前一个节点
	for (int i = 0; i < m - 1; i++) {
		pre = pre->next;
	}
	ListNode* leftNode = pre->next;//反转左节点
	ListNode* rightNode = pre;//反转右节点
	for (int i = 0; i < n - m + 1; i++) {
		rightNode = rightNode->next;
	}
	ListNode* end = rightNode->next;//反转后下一个节点
	rightNode->next = nullptr;
	reverseList(leftNode);
	pre->next =rightNode;
	leftNode->next = end;
	return dummy->next;
}
int main() {
    //创建一个链表:1->2->3->4->5
	ListNode* head = new ListNode(1);
	head->next = new ListNode(2);
	head->next->next = new ListNode(3);
	head->next->next->next = new ListNode(4);
	head->next->next->next->next = new ListNode(5);
	ListNode* head1 = new ListNode(1);
	head1->next = new ListNode(2);
	head1->next->next = new ListNode(3);
	head1->next->next->next = new ListNode(4);
	head1->next->next->next->next = new ListNode(5);
	cout << "original List:";
	ListNode* curr = head;
	while (curr != nullptr) {
		cout << curr->val << " ";
		curr = curr->next;
	}
	cout << endl;
	ListNode* reverse = reverseList(head);
	ListNode* reverse_mid = ReverseBetween(head1,2,4);
	curr = reverse;
	cout << "reversed list:";
	while (curr != nullptr) {
		cout << curr->val << " ";
		curr = curr->next;
	}
	cout << endl;
	ListNode* curr1 = reverse_mid;
	cout << "reversed mid_list:";
	while (curr1 != nullptr) {
		cout << curr1->val << " ";
		curr1 = curr1->next;
	}
	cout << endl;
	system("pause");
	return 0;
}

结果

在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值