leetcode92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

 ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(head==NULL)
            return NULL;
        ListNode* dummy = new ListNode(0);
        dummy->next=head;
        ListNode* pre=dummy;
        for(int i=0;i<m-1;i++){ //从0开始,所以是m-1
            pre=pre->next;
        }
        ListNode* start=pre->next;
        ListNode* then=start->next;
        for(int i=0;i<n-m;i++){
            start->next=then->next;
            then->next=pre->next;
            pre->next=then;
            then=start->next;
        }
        return dummy->next;
    }
};

方法:和反转链表1差不多,区别有以下:
1.设置了dummyhead,返回的时候直接返回dummy->next(头结点);即可
2.pre指针为m的前一个。
3.ListNode* dummy = new ListNode(0); new的用法(manage dynamic storage):
case1:

int *x = new int;       //开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针)
int *a = new int(100);  //开辟一个存放整数的空间,并指定该整数的初值为100,返回一个指向该存储空间的地址

4.过程:
1 -> 2 -> 3 -> 4 -> 5 -> NULL
1 -> 3 -> 2 -> 4 -> 5 -> NULL
1 -> 4 -> 3 -> 2 -> 5 -> NULL

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值