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.



template <class TYPE>

class doublyLinkedList
	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;

	doublyLinkedList(TYPE emptyValue);
	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();}


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)
		head = new Node(data, NULL, NULL);
		head->prev = head->next = head;
		head = new Node(data,head->prev,head->next);
		head->prev->next = head->next->prev = head

Edited by cplusplusrookie: n/a

6 Years
Discussion Span
Last Post by Narue

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. 

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


Edited 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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.