题目
(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;
}