牛客网编程题——链表内指定区间反转

#include<iostream>

using namespace std;
//创建节点
class Listnode {
public:
	int data;
	Listnode* next;
	Listnode(int x) :data(x), next(nullptr) {}
};
//创建链表
Listnode* createList(int n) {
	//定义一个头节点
	Listnode* head = nullptr;
	//prev用来记录前一个节点
	Listnode* prev = nullptr;
	for (int i = 1; i <= n; i++) {
		//创建新的节点 new
		Listnode* newnode = new Listnode(i);
		if (head == nullptr) {
			head = newnode;
		}
		else {
			//表示将新节点连接到链表中,即将新节点自己的地址放入前一个节点的next中(或者将前一个节点的地址指向新节点)
			prev->next = newnode;
		}
		//直接将新节点赋值给prev,用于更新前一个节点,prev里就是新节点的data和next
		prev = newnode;
	}
	return head;//返回头节点
}

class Solution {
public:
	Listnode* reverseBetween(Listnode* head, int m, int n) {
		//加个表头
		Listnode* res = new Listnode(-1);
		res->next = head;
		//前序节点
		Listnode* pre = res;
		//当前节点
		Listnode* cur = head;
		//找到m
		for (int i = 1; i < m; i++) {
			pre = cur;
			cur = cur->next;
		}
		//从m反转到n
		for (int i = m; i < n; i++) {
			Listnode* temp = cur->next;
			cur->next = temp->next;
			temp->next = pre->next;
			pre->next = temp;
		}
		//返回去掉表头
		return res->next;
	}
};


//打印链表
void printList(Listnode* head) {
	while (head != nullptr) {
		cout << head->data << " ";
		head = head->next;
	}
	cout << endl;
}

//释放空间
void deleteList(Listnode* head) {
	while (head != nullptr) {
		Listnode* temp = head;
		head = head->next;
		delete temp;
	}
}

int main() {

	int element = 0;
	int m = 0;
	int n = 0;
	cin >> element;
	cin >> m>>n;
	//创建链表
	Listnode* head = createList(element);
	//打印链表
	cout << "原链表为:";
	printList(head);
	//反转链表
	Solution solution;
	Listnode* reversedHead = solution.reverseBetween(head,m,n);
	cout << "反转链表为:";
	printList(reversedHead);
	//释放内存
	deleteList(head);
	return 0;
}

测试用例:

5 2 4 #element=5生成1到5的链表,指定区间[2,4]进行反转

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值