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 :: string to number in c++ 
Cpp :: random number in a range c++ 
Cpp :: C++ do...while Loop 
Cpp :: c++ functions 
Cpp :: cases in cpp 
Cpp :: http.begin arduino not working 
Cpp :: in c++ the default value of uninitialized array elements is 
Cpp :: access part of string in c++ 
Cpp :: switch case c++ 
Cpp :: for loop with array c++ 
Cpp :: iteraate through a vector 
Cpp :: what is the associative property of an operator 
Cpp :: height of bst cpp 
Cpp :: c++ typeid 
Cpp :: how to remove an element from a vector by value c++ 
Cpp :: check uppercase c++ 
Cpp :: initialize 2d vector 
Cpp :: c++ for else 
Cpp :: get value of enum cpp 
Cpp :: remove decimal c++ 
Cpp :: what is c++ used for 
Cpp :: run cmd command c++ 
Cpp :: c++ print 3d cube 
Cpp :: c++ string size 
Cpp :: find second highest number in c++ 
Cpp :: inline function in c++ 
Cpp :: currency converter c++ 
Cpp :: c++ namespace 
Cpp :: c++ do every 1 minutes 
Cpp :: c++ erase remove 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =