题目在下面写出来了
#include<iostream>
using namespace std;
class ListNode00
{
public:
int val;
ListNode00* next;
};
void test00()
{
ListNode00 a;
ListNode00 b;
ListNode00 c;
ListNode00 d;
ListNode00 e;
a.val = 10;
b.val = 20;
c.val = 30;
d.val = 40;
e.val = 50;
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = NULL;
ListNode00* head = &a;
while (head)
{
cout << head->val << " ";
head = head->next;
}
}
//1链表逆序 -- 直接逆序
class ListNode01
{
public:
int val;
ListNode01* next;
ListNode01(int x) :val(x), next(NULL) {}
};
class Solution1
{
public:
ListNode01* reverseList(ListNode01* head)
{
ListNode01* new_head = NULL; //指向新链表头节点的指针
while (head)
{
ListNode01* next = head->next; //备份head->next;
head->next = new_head; //更新head->next
new_head = head; //移动new_head
head = next; //遍历链表
}
return new_head; //返回新链表的头节点
}
};
void test01()
{
ListNode01 a(10);
ListNode01 b(20);
ListNode01 c(30);
ListNode01 d(40);
ListNode01 e(50);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution1 solve;
ListNode01* head = &a;
cout << "before reverse: " << endl;
while (head)
{
cout << head->val<<" ";
head = head->next;
}
cout << endl;
head = solve.reverseList(&a);
cout << "after reverse: " << endl;
while (head)
{
cout << head->val<<" ";
head = head->next;
}
cout << endl;
}
//从链表的m到n的位置逆序,上面的升级版1<=m<n<=链表长度
class ListNode02
{
public:
int val;
ListNode02* next;
ListNode02(int x) :val(x), next(NULL) {}
};
class Solution2
{
public:
ListNode02* reverseList(ListNode02* head,int m,int n)
{
int change_len = n - m + 1;
ListNode02* pre_head = NULL;
ListNode02* result = head;
while (head && --m) //将head向前移动m-1个位置
{
pre_head = head;
head = head->next;
}
ListNode02* modify_list_tail = head;
ListNode02* new_head = NULL;
while (head && change_len) //逆置change_len个节点
{
ListNode02* next = head->next;
head->next = new_head;
new_head = head;
head = next;
change_len--;
}
modify_list_tail->next = head;
if (pre_head)
{
pre_head->next = new_head;
}
else
{
result = new_head;
}
return result;
}
};
void test02()
{
ListNode02 a(10);
ListNode02 b(20);
ListNode02 c(30);
ListNode02 d(40);
ListNode02 e(50);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution2 solve;
ListNode02* head = &a;
cout << "before reverse: " << endl;
while (head)
{
cout << head->val << " ";
head = head->next;
}
cout << endl;
head = solve.reverseList(&a,2,4);
cout << "after reverse: " << endl;
while (head)
{
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main()
{
//test00();
test02();
system("pause");
return 0;
}