Answers for "c++ doubly linked list"

C++
1

doubly linked list c++ code

/*
* Doubly linked list implementation in c++.
* operations:
* 1-> Insert at head.
* 2-> print forward.
* 3-> print reverse order.
*/
#include<iostream>
using namespace std;
struct node
{
	int data;
	node* next;
	node* prev;
};
class d_list
{
private:
	node* head;
	node* GetNewNode(int n)
	{
		node* newNode = new node();
		newNode->data = n;
		newNode->next = NULL;
		newNode->prev = NULL;
		return newNode;
	}
public:
	d_list()
	{
		head = NULL;
	}
	void InsertAtHead(int n)
	{
		node* temp = GetNewNode(n);
		if (head == NULL)
		{
			head = temp;
			return;
		}
		head->prev = temp;
		temp->next = head;
		head = temp;
	}
	void print()
	{
		node* t = head;
		cout << "Forward: ";
		while (t!=NULL)
		{
			cout << t->data << " ";
			t = t->next;
		}
		cout << "\n";
	}
	void print_reverse()
	{
		node* t = head;
		while (t->next != NULL)
		{
			t = t->next;
		}
		//reverse
		cout << "reverse: ";
		while (t != NULL)
		{
			cout << t->data << " ";
			t = t->prev;
		}
		cout << "\n";
	}
};

int main()
{
	d_list l;     //object from class doubly list
	l.InsertAtHead(1);
	l.InsertAtHead(2);    //function insert at beginning
	l.InsertAtHead(3);
	l.print();             //List should print: 3 2 1
	l.print_reverse();     //List should print: 1 2 3
	return 0;
}
Posted by: Guest on December-21-2021
1

c++ doubly linked list

#include <iostream>
#include <list>

// For help in printing lists
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list) {
    for (const auto &i : list) {
        ostr << ' ' << i;
    }
    return ostr;
}


int main() {

    std::list<int> list1 = { 5,9,1,3,3 };
    std::list<int> list2 = { 8,7,2,3,4,4 };

    list1.sort();
    list2.sort();
    std::cout << "list1:  " << list1 << '\n';
    std::cout << "list2:  " << list2 << '\n';
    list1.merge(list2);
    std::cout << "merged: " << list1 << '\n';

    return 0;
}
Posted by: Guest on April-05-2022

Code answers related to "c++ doubly linked list"

Browse Popular Code Answers by Language