1

I'm trying to add a node to the beginning of a linked list. Here is my code for it, but when I run tests on it, it doesn't work. Any ideas on what I might be doing incorrectly? Thanks in advance for your help!

void List<T>::insertFront(T const & insert)
{
    ListNode * newNode = new ListNode(insert);
    if (head != NULL)
    {
        head->prev = newNode;
        head = head->prev;
        head->prev = NULL;
    }
    else
    {
        head = newNode;
        tail = newNode;
    }
}

2 Answers 2

3

A doubly linked list is linked 2 ways, you're only attaching the new node in one way.

You need a:

newnode->next = head;

in there before you unlink the old head.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this.

Below method is only taking the input and making a doubly link list

node DoublyLinkedList()
{
node *list, *tptr, *nptr;
int n, item;
cout << "Enter numbers of node: ";
cin >> n;
list = NULL;
tptr = NULL;
for (int i = 0; i < n; i++)
{
    //Input new node value
    cout << "Enter Item " << i + 1 << ": ";
    cin >> item;
    //Creating new node
    nptr = new(node);
    nptr->back = NULL;
    nptr->data = item;
    nptr->next = NULL;

    if (list == NULL)
    {
        list = nptr;
        tptr = nptr;
    }
    else
    {
        tptr->next = nptr;
        nptr->back = tptr;
        tptr = nptr;
    }
}
cout << endl;
tptr = list;
while (tptr != NULL)
{
    cout << tptr->data;
    tptr = tptr->next;
    if (tptr != NULL)
    {
        cout << "<=>";
    }
}
return *list;
}

Inserting the the new node using below method

void InsertToDoubly()
{
node *list, *tptr, *nptr, *pptr;
int newItem;
list = new(node);
tptr = NULL;
pptr = NULL;
*list = DoublyLinkedList(); // See this method implementation above.
cout << endl;
cout << "Input new node value to insert: ";
cin >> newItem;

nptr = new(node);
nptr->back = NULL;
nptr->data = newItem;
nptr->next = NULL;

tptr = list;
int i = 0;
while (tptr != NULL && tptr->data < newItem)
{
    pptr = tptr;
    tptr = tptr->next;
    i++;
}
if (i == 0)
{
    // Inserting at the beggining position.
    nptr->next = tptr;
    tptr->back = nptr;
    list = nptr;
}
else if (tptr == NULL)
{
    //Inserting at the last position
    pptr->next = nptr;
    nptr->back = pptr;
}
else
{
    //Inserting into the middle position
    pptr->next = nptr;
    nptr->back = pptr;
    nptr->next = tptr;
    tptr->back = nptr;
}
tptr = list;
ShowNode(tptr);
cout << endl;
}

Main method

int main()
{
   InsertToDoubly();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.