Inverted output of the linked list and reverse output of the 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 <iostream>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<nLength;i++){Node* ptr = new Node;ptr->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<<p->key<<endl;p=p->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<
Create a chain table that stores 10 numbers and output them in reverse order.
# Include <stdio. h>
# Include <malloc. h>
Typedef struct LNode
{
Int data;
Struct LNode * next;
} LNode, * LinkList;
Void creatLinkList (LinkList & p)
{
Int I, n;
LinkList q = NULL, q1 = NULL;
P = (LinkList) malloc (sizeof (struct LNode ));
Q = p;
Printf ("please input the data in 1 times :");
Scanf ("% d", & n );
Q-> data = n;
Q-> next = NULL;
For (I = 1; I <10; I ++)
{
Q1 = (LinkList) malloc (sizeof (struct LNode ));
Q-> next = q1;
Printf ("please input the data in % d times:", I + 1 );
Scanf ("% d", & n );
Q1-> data = n;
Q1-> next = NULL;
Q = q1;
}
}
Void showListInverse (LinkList p)
{
Int I = 0, a [10] = {0 };
While (p-> next! = NULL)
{
A [I] = p-> data;
P = p-> next;
I ++;
}
A [I] = p-> data;
For (I = 9; I> = 0; I --)
{
Printf ("% d \ n", a [I]);
}
}
Int main (void)
{
LinkList head = NULL;
CreatLinkList (head );
ShowListInverse (head );
Return 0;
}
Bidirectional linked list reverse output
1. printf ("xiayigejiedian:") in creat (); the previous sentence (struct student *) malloc (LED );
, It should be p1 = (struct student *) malloc (LED); always 0. This is because this sentence is incorrect. If p1 is not updated, the node's back points to itself.
2. Since you want to output 0 as a node, create () will use p2-> next = p1 at last;
P1-> back = p2;
Last = p1;
3. print () the final judgment condition should be while (p! = NULL );