leetcode第一刷_Reverse Linked List II

本文介绍了一种在链表中翻转指定区间的算法实现。该方法通过一次遍历完成节点翻转,并确保了翻转部分与原链表正确连接。文章提供了完整的C++代码示例。

翻转链表绝对是终点项目,应该掌握的,这道题要求的是翻转一个区间内的节点,做法其实很相似,只不过要注意判定开始是头的特殊情况,这样head要更新的,还有就是要把翻转之后的尾部下一个节点保存好,要么链表就断掉了。一趟就可以,遇到节点直接翻转,最后把整个翻转的链表再翻转一次,就实现了。

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(head == NULL || m==n)    return head;
        ListNode *l1, *l2, *pNode = head, *pre = NULL, *nt, *ntt, *nttt;
        int i = 1;
        while(pNode){
            if(i<m) {pre = pNode; i++; pNode = pNode->next;}
            else{
                l1 = pNode;
                nt = l1;
                ntt = l1->next;
                l1->next = NULL;
                while(ntt&&i<n){
                    nttt = ntt->next;
                    ntt->next = nt;
                    nt = ntt;
                    ntt = nttt;
                    i++;
                }
                l2 = ntt;
                l1->next = l2;
                if(pre){
                    pre->next = nt;
                    return head;
                }else{
                    return nt;
                }
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值