Inverted output of linked list

Source: Internet
Author: User

Inverted output of linked list

The inverted output of the linked list, which we may think of, is to flip the linked list and traverse it again. In this case, the time complexity is O (n), but the disadvantage is that the Code is slightly complicated. Or open up an array, traverse a linked list sequentially, copy the elements to the array, and output the array in reverse order. In fact, the time complexity of this question cannot be lower than O (n). However, considering stack usage, the Code may be very simple. The Code is as follows:

#include 
 
  using namespace std;struct Node{int key;Node* next;};Node* createList(int arr[],int nLength);void printList(Node* head);void reversePrint(Node* head);void clearList(Node* head);void main(){int arr[] = {1,3,5,7,9};int nLength = sizeof(arr)/sizeof(arr[0]);Node* head = createList(arr,nLength);printList(head);reversePrint(head);clearList(head);}Node* createList(int arr[],int nLength){Node* head = new Node;head->key = arr[0];head->next = NULL;Node *p = head;for(int i=1;i
  
   key = arr[i];ptr->next = NULL;p->next = ptr;p = p->next;}return head;}void printList(Node* head){Node* p = head;while( p!= NULL ){cout<
   
    key<
    
     next;}}void clearList(Node* head){Node* p = head;Node* ptr;while( p!= NULL ){ptr = p->next;delete p;p = ptr;}}void reversePrint(Node* head){if( head != NULL ){if( head->next != NULL )reversePrint(head->next);}cout<
     
      key<
      
       

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.