List of linked list reversal

Source: Internet
Author: User

Idea 1:O (n^2).

"Civet cat for Prince", do not change the structure of the list, only Exchange LEN/2 times. However, in this function, the positioning function is used, the positioning function is actually traversing through the entire list, so the overall efficiency is very low to reach O (n^2).

Single-linked list inversion (O (n^2)) void Reverselist (node* head) {   int count = Numofnodes (head);   Swap for   (int i=1; i<=count/2; i++)   {      node* p1 = Locatenodei (Head, i);      node* P2 = Locatenodei (Head, count+1-i);      Swap (P1->value, p2->value);}   }
Idea 2:O (n).

In the most general case (there is no pre-written auxiliary function, that is, only the head points to a single linked list). O (n) efficiency can be achieved.

The procedure is to traverse with three neighboring pointers, changing the direction of the pointer while traversing. Of course, we should pay attention to the number of linked lists, and the disposal of the chain.

Single-linked list inversion (O (n)) node* ReverseList2 (node* Head) {   if (Head==null | | Head->next==null)//empty chain and single node   {      return Head;   }   node* p1 = Head;   node* P2 = head->next;   node* P3 = head->next->next;      if (p3==null)//Only two nodes   {      p1->next = NULL;      P2->next = p1;      Head = p2;      return Head;   }   else//At least three nodes   {      p1->next = NULL;      while (P3!=null)      {         p2->next = p1;         Three pointers move backward one         p1=p2;         P2=P3;         p3=p3->next;      }      P2->next = p1;      Head = p2;      return Head;  }}

List of linked list reversal

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.