Reverse Linked list and Reverse Linked list II

Source: Internet
Author: User

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

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.