翻转链表中第m个节点到第n个节点的部分
注意事项
m,n满足1 ≤ m ≤ n ≤ 链表长度
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null
主要思想:找到需要翻转的m,n结点及其前一、后一结点,以便后期插入使用。
需要考虑边界情况:
1、当m=1时,无前向结点
2、m,n均在中间时与n在结尾时可以归类为同一种情况
3、注意不要忘记num++;
代码如下:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
ListNode * reverseBetween(ListNode * head, int m, int n) {
// write your code here
int num = 1;
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* p;
ListNode* q;
if(head == NULL && head->next == NULL)
{
return head;
}
while(num != m)
{
pre = cur;
cur = cur->next;
num++;
}
p = cur;//将p指向m结点,pre则为m前向结点,此时num=2
while(num != n)
{
cur = cur->next;
num++;
}
cur = cur->next;
q = cur; //此时cur、q指向n结点的后向结点
if(pre == NULL)//即m==1
{
head = reverse(p , q);
p->next = cur;
}
else
{
pre->next = reverse(p , q);
p->next = cur;
}
return head;
}
ListNode* reverse(ListNode* head,ListNode* q) //翻转的思想很简单,就是3节点翻转思想,cur指向pre ,pre= cur,cur = next。另外不改变head有好处。
{
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* next=NULL ;
while(cur != q)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;//此为翻转链表后的第一个结点
}
};