Leetcode92-反转链表Ⅱ

题目

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

示例

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

code

注意点:

  1. 只有一个元素的情况
  2. 从第一个元素开始逆置的情况
    解决办法:在head前再加一个链pre_headpre_head
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        int turn = n - m + 1;
		ListNode* pre_head = new ListNode(-1);
		pre_head->next = head;//head前加一个链

		ListNode* pre = pre_head;
		for(int i=1;i<m;i++)
			pre= pre->next;
		ListNode* mark_pre = pre,* mark_cur = pre->next, *cur = pre->next;

		while (cur&&turn--)
		{
			ListNode* temp = cur->next;
			cur->next = pre;
			pre = cur;
			cur = temp;
		}
		mark_cur->next = cur;
		mark_pre->next = pre;
	
		return pre_head->next;
		
		
    }
};

class solution在main函数里的测试方法

#include <iostream>
using namespace std;

struct Node {
	int data;
	Node* next;
	Node();
	Node(int item, Node* address = NULL);//initialize
};
Node::Node() {
	next = NULL;
}
Node::Node(int item, Node* address) {
	data = item;
	next = address;
}

class solution {
public:
	Node* reverseBetween(Node* head, int m, int n) {
		int turn = n - m + 1;
		Node* pre_head = new Node(-1);
		pre_head->next = head;//head前加一个链

		Node* pre = pre_head;
		for(int i=1;i<m;i++)
			pre= pre->next;
		Node* mark_pre = pre,* mark_cur = pre->next, *cur = pre->next;

		while (cur&&turn--)
		{
			Node* temp = cur->next;
			cur->next = pre;
			pre = cur;
			cur = temp;
		}
		mark_cur->next = cur;
		mark_pre->next = pre;
	
		return pre_head->next;
		
	}
};
int main() {
	int f;
	int num;
	cin >> f;
	solution solve;
	/*****输入*****/
	cin >> num;
	Node* head = new Node(num);
	Node* p = head;
	for (int i = 1; i < f; i++) {
		cin >> num;
		Node* newptr = new Node(num);
		p->next = newptr;
		p = newptr;
	}
	p->next = NULL;
    
    /*****代入实例函数测试*****/
	int m, n;
	cin >> m >> n;
	head = solve.reverseBetween(head, m, n);
    
    /*****输出*****/
	Node* q = head;
	while (q)
	{
		cout << q->data << " ";
		q = q->next;
	}
	
    /*****delete*****/
	while (head) {
		Node* t = head;
		head = head->next;
		delete t;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值