Leetcode (Reverse): Linked List II

Source: Internet
Author: User

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.

Test Instructions: reverses the linked list, reversing the linked list at the specified position.

idea: refer to Here, the main is to find to reverse the beginning of the linked list of the junction of the reverse, and then one by one reversal, and finally and its side of the part to connect.

Code:

 PublicListNode Reversebetween (ListNode head,intMintN) {if(head==NULL)return NULL; ListNode Q=NULL; ListNode P=Head;  for(inti=0;i<m-1;i++) {Q=p; P=P.next; } ListNode End=p; ListNode Ppre=p; P=P.next;  for(inti=m+1;i<=n;i++) {ListNode Pnext=P.next; P.next=Ppre; Ppre=p; P=Pnext; } End.next=p; if(q!=NULL) Q.next=Ppre; ElseHead=Ppre; 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.