leetcode_ReverseLinkedListII

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.

很多边界问题  很难在短时间写出bug free的代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        ListNode *ho=NULL, *p=NULL,*s=NULL, *h=NULL;
        ListNode *newhead = new ListNode(-1);
        p=newhead;
        p->next = head;
        for(int i =1 ;i<=m-1;i++)
        {
            p=p->next;
        }
        ho=h=p->next;    //保存这个节点
        p->next=NULL;
        for(int i =m; i<=n ; i++){
            s= h;
            h=h->next;
            s->next=p->next;
            p->next = s;
        }
        ho->next = h;
        return newhead->next;
        
    }
};
点赞