在双链表中插入节点

时间:2012-09-27 15:49:12

标签: c++ linked-list

我正在尝试将节点添加到链接列表的开头。这是我的代码,但是当我对它运行测试时,它不起作用。关于我可能做错的任何想法?在此先感谢您的帮助!

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 个答案:

答案 0 :(得分:3)

双向链表是以两种方式链接的,你只是以一种方式附加新节点。

你需要一个:

newnode->next = head;

在那之前你取消旧头的链接。

答案 1 :(得分:0)

尝试一下。

下面的方法仅接受输入并创建一个双向链接列表

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;
}

使用以下方法插入新节点

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;
}

主要方法

int main()
{
   InsertToDoubly();
}