"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