Search
 
SCRIPT & CODE EXAMPLE
 

CPP

print linked list reverse order in c++

#include<iostream>
using namespace std;

struct node
{
	int data;
	node* next;
};
node* insert(node* head, int value)
{
	node* temp1 = (node*)malloc(sizeof(node));
	temp1->data = value;
	temp1->next = NULL;
	if (head == NULL)
	{
		head = temp1;
	}
	else
	{
		node* temp2 = head;
		while (temp2->next!=NULL)
		{
			temp2 = temp2->next;
		}
		temp2->next = temp1;
	}
	return head;
}
void print(node* p)
{
	if (p == NULL)
		return;
	cout << p->data << " ";
	print(p->next);
}
void reverse_order(node* p)
{
	if (p == NULL)
		return;
	reverse_order(p->next);
	cout << p->data << " ";
}
int main()
{
	node* head = NULL;
	head = insert(head, 1);
	head = insert(head, 2);
	head = insert(head, 3);
	print(head);             //list: 1 2 3.
	cout << endl;
	reverse_order(head);    //list: 3 2 1.

	return 0;
}
Comment

Reverse a linked list geeksforgeeks in c++

/* 
   problem link: https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1/?page=1&difficulty[]=0&status[]=unsolved&sortBy=submissions#
*/
///////////////////////////////////////////////////////////////////////////////////////////
class Solution
{
    public:
    //Function to reverse a linked list.
    struct Node* reverseList(struct Node *head)
    {
        // code here
        // return head of reversed list
        Node *p, *c, *n;
        p=NULL;
        c=head;
        while(c!=NULL)
        {
            n=c->next;
            c->next=p;
            p=c;
            c=n;
        }
        head=p;
        return head;
    }
    
};
Comment

PREVIOUS NEXT
Code Example
Cpp :: move elements from vector to unordered_set 
Cpp :: recursive factorial of a number 
Cpp :: auto in c++ 
Cpp :: cout stack in c++ 
Cpp :: how to get last element of set 
Cpp :: c++ online compiler 
Cpp :: count number of char in a string c++ 
Cpp :: Program to print full pyramid using 
Cpp :: c++ classes 
Cpp :: clear map in C++ 
Cpp :: cpp vector popback 
Cpp :: time complexity 
Cpp :: shift element to end of vector c++ 
Cpp :: create vector of specific size c++ 
Cpp :: C++ Taking Multiple Inputs 
Cpp :: heap allocated array in c ++ 
Cpp :: cpp language explained 
Cpp :: binary tree 
Cpp :: binary to decimal online converter 
Cpp :: c++ overloading by ref-qualifiers 
Cpp :: C++ CHEAT SHEAT 
Cpp :: Restart the computer in c++ after the default time (30) seconds. (Windows) 
Cpp :: COs trigonometric function 
Cpp :: how does sorting array works in c++ 
Cpp :: cap phat dong mang 2 chieu trong c++ 
Cpp :: increment integer 
Cpp :: c++ dynamic array 
Cpp :: big o notation practice c++ 
Cpp :: Create an algorithm to identify what is the next largest element on a stack (using stack/queue operations only) INPUT: [ 10, 3, 1, 14, 15, 5 ] OUTPUT: 10 - 14 3 - 14 1 - 14 14 - 15 15 - -1 5 - -1 
Cpp :: unreal engine c++ bind action to function with parameter 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =