簡體   English   中英

在雙鏈表中插入節點

[英]Inserting a node in a double 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;
    }
}

雙向鏈表是以兩種方式鏈接的,您只是以一種方式附加新節點。

你需要一個:

newnode->next = head;

在你取消舊頭之前的那里。

嘗試這個。

下面的方法只是輸入並制作雙重鏈接列表

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM