开发者

Using C++, how can I move nodes backwards in a singly linked list?

开发者 https://www.devze.com 2023-02-13 10:06 出处:网络
void currentbac() { if (current == first) cout << \"This is the beginning of the list.\" << endl;
void currentbac()
{
    if (current == first)
        cout << "This is the beginning of the list." << endl;
    else
    {
        list *previous;
        previous = first;
        while (previous->next != current)
        {
            previous = previous->next;
        }
        current = previous;
    }
}

This is the code I put for moving the "current" pointer backwards. I 've initialized both current and first to null at the start of my code.

What I really want is to move the node through my list of nodes forward or backward.and then I want to insert a n开发者_如何学运维ode whereever neccessary. I know there are doubly linked lists but if someone can post the code for doubly linked list moving thats fine too. But I wanted to know if you can move using a single linked list.

Also

void addmiddle()
{
    if (current == NULL)
    {
        cout << "Current is invalid" << endl;
        return;
    }
    if (current->next == NULL)
       addending();
    else
    {
        list *newlist;
        newlist=new list;
        cout << "Enter your name:" ;
        cin >> newlist->name;
        cout << "Enter your age:" ;
        cin >> newlist->age;
        cout << "Enter your height:" ;
        cin >> newlist->height;
        newlist->next=current->next;
        current->next=newlist;
    }
}

^ this is my code for adding a node in the middle of the list.I wanted to know how it works cos apparently im not able to move "Current"backwards.

0

精彩评论

暂无评论...
验证码 换一张
取 消