LeetCode—单链表翻转

Reverse Linked List II


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.

/**
 * 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)
    {

        if (head == NULL)
            return NULL;

        ListNode * pBeginNode = NULL ;
        ListNode * pEndNode = NULL;
        ListNode * pmNode = head;
        ListNode * ptempNode = NULL;
        ListNode * pnNode = NULL;
        
        for(int i = 0; i < (m-1); i++) //next;
        }
        ptempNode = pmNode;
        
        ListNode *pPre = pmNode;
        pmNode = pmNode->next;
        for(int i = 0; i < (n-m); i++) //next;
            pmNode->next = pPre;
            pPre = pmNode;
            pmNode = pNext;
        }
        ptempNode->next = pmNode;
        
        if(pBeginNode)
        {
            pBeginNode->next = pPre;
        }
        else
        {
            head = pPre;
        }
        return head;
    }
};

 

你可能感兴趣的:(单链表,leetcode)