14. Reverse Linked List II

Source: Internet
Author: User
Reverse Linked List II

Reverse a linked list from positionMToN. Do it in-place and in one-pass.

For example: Given1->2->3->4->5->NULL,M= 2 andN= 4,

Return1->4->3->2->5->NULL.

Note:GivenM,NSatisfy the following condition: 1 ≤MN≤Length of list.

 

Conclusion: It is actually a reverse linked list. It is only the middle part of the reversal. Note that the cursor of the first node is saved. If the first node is the header node, note that the tail node of the anti-Rotor String is changed to the header node.

/** * 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 *preNode1, *node1, *node2; preNode1 = node1 = node2 = NULL; int cnt = 0; for(ListNode *p = head; p != NULL; p = p->next) { cnt++; if(cnt == m-1) preNode1 = p; // hidden: m > 1 if(cnt == m) node1 = p; if(cnt == n) { node2 = p; break; } } ListNode *tail = node2->next; // must take out as a tag. ListNode *pre = tail, *post; while(node1 != tail) { post = node1->next; node1->next = pre; pre = node1; node1 = post; } if(m > 1) { preNode1->next = node2; return head;} return node2; // node1 is the 1st node. } };

 

14. 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.