Hi,

I am doing a program using Doubly-Linked List. I am just studying C++, and still new in this field. My question are:

- How can I make a method which inserts a new node before the currently selected node, then makes the new node the current node?
- How can I make a method which inserts a new node after the currently selected node, then makes the new node the current node?

I came up with some ideas, please check it out. Your help is greatly appreciated.

doublyLinkedList.h

#ifndef _DOUBLYLINKEDLIST_H
#define _DOUBLYLINKEDLIST_H

template <class TYPE>

class doublyLinkedList
{
private:
	struct Node
	{
		TYPE data;
		Node *next;
		Node *prev;
		Node(TYPE t,Node* p, Node* n): data(t),prev(p),next(n){}
	};
	Node *head;
	Node *tail;

public:
	doublyLinkedList();
	doublyLinkedList(TYPE emptyValue);
	~doublyLinkedList();
	void InsertBefore(TYPE data);
	void InsertAfter(TYPE data);
	TYPE GetValue();
	TYPE NextValue();
	TYPE PreviousValue();
	bool empty() const {return(!head || !tail );}
	operator bool() const{return !empty();}
};

#endif // _DOUBLYLINKEDLIST_H

I already created a method for insert before the currently selected node, but I am not sure it is right or not. And I need some ideas for insertAfter method.

template <class TYPE>
void doublyLinkedList<TYPE>::insertBefore(TYPE data)
{
	if(empty())
	{
		head = new Node(data, NULL, NULL);
		head->prev = head->next = head;
	}
	else
	{
		head = new Node(data,head->prev,head->next);
		head->prev->next = head->next->prev = head
	}
}

Edited 5 Years Ago by cplusplusrookie: n/a

Seems like your creating a deque (double sided queue) which is part of the STL library.

Honestly I don't like heads/tail naming but that's just a personal thing. Before/After is a bit more clear or front/back.

template<typename T>
void doublyLinkedList<T>::insertBefore(const T& data)
{
    //Well if Before means at the absolute front than the previous head should have nullptr for it's "prev" value
    //So this one shouldn't have a prev value as it's replacing it
    head = new Node<T>(data,head,nullptr);
    //If prevhead was empty who cares head should be init'd to nullptr so it just passes nullptr so this becomes the new head with no      //head/tails value attached. No need doing an empty check for the front or back ends. 
}

//Constructor
 Node::Node(const T& data,Node<T>* tail, Node<T>* head) : m_data(data), m_tail(tail), m_head(head)
{
  //Switch tail
    if(tail)
  tail->head = this;
    if(head)
  head->tail = this;


}

Edited 5 Years Ago by ChaseRLewis: n/a

In anticipation of questions like this, I wrote a tutorial on linked lists. The code is in C, but the concepts apply for any language.

This article has been dead for over six months. Start a new discussion instead.