36. 翻转链表 II

翻转链表中第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;//此为翻转链表后的第一个结点
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值