如何遍历链表?

时间:2018-02-22 21:18:25

标签: c++ pointers data-structures linked-list doubly-linked-list

我可以从头到尾遍历双向链表,打印出列表并相应地对元素进行排序。但我不能从Tail指针遍历Head指针。我想通过向后遍历来打印列表。我也是想要从排序列表中删除元素并显示内容。

1 个答案:

答案 0 :(得分:1)

您的SortedInsert()方法正在分配2个Node个对象,而不是正确初始化它们。它应该只分配1个Node对象,因为您只插入1个元素。当列表中包含1个Node对象时,HeadTail指针应指向该Node个对象,而不是指向不同的Node个对象。< / p>

请改为尝试:

void DoublyLinkedList::SortedInsert(const int& new_element) {

    Node* np = new Node(new_element);

    if (!Head)
    {
        Head = np;
        Tail = np;
    }
    else if (new_element < Head->Element)
    {
        np->Next = Head;
        Head->Prev = np;
        Head = np;
    }
    else
    {
        Node *cur = Head->Next;
        while ((cur) && (new_element >= cur->Element))
            cur = cur->Next;

        if (cur)
        {
            np->Prev = cur->Prev;
            np->Next = cur;
            cur->Prev->Next = np;
            cur->Prev = np;
        }
        else
        {
            Tail->Next = np;
            np->Prev = Tail;
            Tail = np;
        }
    }    
}

删除Node对象时,这是一个简单的遍历,用于查找Node,然后更新周围的Node个对象,使其不再指向它,例如:

void DoublyLinkedList::Delete(const int& del_element)
{
    Node *cur = Head;
    while (cur)
    {
        if (cur->Element == del_element)
        {
            if (cur->Prev)
                cur->Prev->Next = cur->Next;
            if (cur->Next)
                cur->Next->Prev = cur->Prev;
            if (cur == Head)
                Head = cur->Next;
            if (cur == Tail)
                Tail = cur->Prev;
            delete cur;
            break;
        }
        cur = cur->Next;
    }
}