题目链接:
题目描述:
给一个链表,例如1->2->3->4->5->NULL。
m=2,n=4,将m到n之间的链表反向。1->4->3->2->5->NULL
分析:
和链表反向没啥区别,就是多了一些控制而已。只是在写reverseN函数时,开始是想用指针的引用来写的,QAQ然而发现,我还是写的磕磕绊绊,之后补上。
代码:
class Solution {
public:
ListNode* reverseN(ListNode* &head, ListNode* ptr, int cnt, int n){
if (cnt == n){
head = ptr;
return head;
}
ListNode* pNext=reverseN(head, ptr->next, cnt + 1, n);
ListNode* tmp = pNext->next;
pNext->next = ptr;
ptr->next = tmp;
return ptr;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m == n){
return head;
}
ListNode* pHead = (ListNode*)malloc(sizeof(ListNode));
pHead->next = head;
int cnt = 1;
ListNode* pre = pHead;
ListNode* cur = head;
while (cur != NULL){
if (cnt == m){
reverseN(cur, cur, cnt, n);
pre->next = cur;
break;
}
cnt++;
pre = cur;
cur = cur->next;
}
return pHead->next;
}
};

本文介绍了一种链表区间反转的方法,通过递归实现从m到n位置的节点反转。给出的C++代码示例详细解释了如何在链表中反转指定区间的节点,并保持其余部分不变。
589

被折叠的 条评论
为什么被折叠?



