/** * Definition of singly-linked-list: * * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ classSolution { public: /** * @param head: The head of linked list. * @param m: The start position need to reverse. * @param n: The end position need to reverse. * @return: The new head of partial reversed linked list. */ ListNode *reverseBetween(ListNode *head, int m, int n){ if (head == NULL || m > n) { returnNULL; }
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ publicclassSolution { /** * @param ListNode head is the head of the linked list * @oaram m and n * @return: The head of the reversed ListNode */ public ListNode reverseBetween(ListNode head, int m , int n) { ListNodedummy=newListNode(0); dummy.next = head; // find the mth node ListNodepremNode= dummy; for (inti=1; i < m; i++) { premNode = premNode.next; } // reverse node between m and n ListNodeprev=null, curr = premNode.next; while (curr != null && (m <= n)) { ListNodenextNode= curr.next; curr.next = prev; prev = curr; curr = nextNode; m++; } // join head and tail before m and after n premNode.next.next = curr; premNode.next = prev; return dummy.next; } }