When the list is completely inverted, only with the configuration of the header, and in another write recursive function reverse list can be called by the main function, the program is as follows:
listnode* reverselist (listnode* head) {
if (head = = NULL) return null;
listnode* P=head;
while (P->next!=null) p=p->next;
Doreverse (head);
return p;
}
listnode* Doreverse (listnode* head) {
if (Head->next==null) return head;
listnode* P=doreverse (Head->next);
P->next = head;
Head->next = NULL;
return head;
}
When partial inverse list, according to different circumstances, modify the main function to deal with different situations can:
listnode* Reversebetween (listnode* head, int m, int n) {
if (head = = NULL) return null;
if (m==n) return head;
listnode* P1=head;
for (int i=m; i>2; i--) {
P1 = p1->next;
}
listnode* Q=head;
for (int i=n; i>1; i--) {
Q = q->next;
}
if (m==1) {
if (q->next==null) {
Doreverse (head);
return q;
}
listnode* q1=q->next;
Q->next = NULL;
Doreverse (head);
Head->next = Q1;
return q;
}
else {
if (Q->next = = NULL) {
listnode* p=p1->next;
Doreverse (P);
P1->next = q;
return head;
}
listnode* p = p1->next;
listnode* q1 = q->next;
Q->next = NULL;
Doreverse (P);
P1->next = q;
P->next = Q1;
return head;
}
}
There are short implementations of code, but I am learning from others, execution speed is similar:
listnode* dummy = new ListNode (0);
Dummy->next = head;
ListNode *lefti = dummy;
for (;--m;--n) Lefti = lefti->next;
ListNode *cur = lefti->next, *rtail = cur, *pre = nullptr;
while (n--) {
listnode* NXT = cur->next;
Cur->next = pre;
Pre = cur;
cur = NXT;
}
Rtail->next = cur; Lefti->next = pre;
Return dummy->next;
Reverse Linked list and Reverse Linked list II