题目
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
示例
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
code
注意点:
- 只有一个元素的情况
- 从第一个元素开始逆置的情况
解决办法:在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;
}