Linked list-reverse Linked list II

Source: Internet
Author: User

"The title requires a direct rollover of the list, not a new space."

One of the key points of this problem is that when m=1, there is no other node (Leetcode test case without head node) in front of the linked list that needs to be flipped, which brings a little difficulty to solving the problem. A more intuitive and convenient idea is to insert a head node in a linked list, which is a lot easier to handle. In addition, you should also pay attention to the settings of various cyclic boundary conditions.

/** Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *};*/structlistnode* Reversebetween (structListnode* Head,intMintN) {structListNode * Pre= (structListNode *)malloc(sizeof(structListNode)); Pre->next=Head; Head=pre;//Insert a head node    structListNode *begin; intI=0;  while(i<m-1) {Pre=pre->Next; I++; } Begin=pre->Next;  for(i=m;i<n;i++)    {        structListNode *p=begin->Next; Begin->next=p->Next; P->next=pre->Next; Pre->next=p; }        returnHead->Next; }

See a very concise code on the Leetcode, the basic idea of the same flexible use of pointers, without adding head node, worship!

listnode* Reversebetween (listnode* head,intMintN) {ListNode**pre = &head;//the address where the head pointer is stored in the pre    intSteps =m;  while(--steps) {pre = & (*pre)Next;} ListNode*cur = *pre;//point to the first node of a flipped list     for(inti = m; I < n; i++) {ListNode*next_n = cur->Next; Cur->next = next_n->Next; Next_n->next = *Pre; *pre =Next_n; }    returnhead;}

Linked list-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.