Leetcode-reverse Linked List II

Source: Internet
Author: User

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->NULL , m = 2 and n = 4,

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

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤length of list.

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: Onelistnode* Reversebetween (listnode* head,intMintN) { A         if(head = = NULL | | m==n)returnhead; -listnode* TP =head; -listnode* h =head; thelistnode* TAIL,*PREV,*CUR,*NXT, *before; -         intCount =0; -          -Prev =NULL; +Cur =head; -NXT = head->Next; +          for(intI=1; i<m;i++{//Find the first node that needs to be reversed. Prev is the precursor node, cur is the current node, and NXT is the successor node APrev =cur; atCur =NXT; -NXT = nxt->Next; -         } -Before =prev;//The node before the reversed part (possibly an empty node, that means the inverse from the first node) -Tail =cur;//Reverse part of the final tail node -          for(inti=m;i<n;i++) {//start the reverse until the last node that needs to be reversed is stopped (the last node that needs to be reversed is processed separately) inCur->next =prev; -Prev =cur; toCur =NXT; +NXT =nxt->Next; -         } theCur->next =prev;//Now Cur is pointing to the last node that needs to be reversed *         if(Before = =NULL) {//If before points to an empty node, it indicates that the head node needs to be changed.  $Head =cur;Panax Notoginseng         } -         Else{//otherwise will "That node before the part that was reversed"Next points to the current node (i.e. the last node that needs to be reversed)
theBefore->next =Cur
+ }
ATail->next =NXT;//The last node of the reversed part to connect to the following part of the list
the returnHead;
+ }
-};

Leetcode-reverse Linked List II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.