簡體   English   中英

在雙向鏈接列表中添加到頭部

[英]Adding to the head in a doubly linked list

我有以下幾點:

typedef struct value value;

struct value{
  value* prev;
  value* next;
  int value;
};

...
//ent = entry
if(entry_head == NULL) { 
 entry_head = ent;
 entry_tail = ent;
 entry_tail->prev = NULL;
}
else { // add to top
 entry_head = ent
 entry_tail = entry_tail->next;
}

當我在列表中插入一些值時,得到以下結果。

Expected: b         Result: a
          a                 b

如何修改它,以使新添加的節點鏈接到先前節點的頂部?

您的代碼未設置足夠的指針。 通常,必須確保新節點的prev是正確的; next是正確的; 前一個條目的next是正確的; 而下一個條目的prev是正確的(小心,如果上一個或下一個條目是NULL)。

假設全局變量為:

value *entry_head = NULL;
value *entry_tail = NULL;

那么插入新value *ent (已經使用值初始化)的代碼為:

if (entry_head == NULL)
{
    assert(entry_tail == NULL);
    entry_head = ent;
    entry_tail = ent;
    ent->next = NULL;
    ent->prev = NULL;
}
else
{
    assert(entry_tail != NULL);
    ent->next = entry_head;
    ent->prev = NULL;
    entry_head->prev = ent;
    entry_head = ent;
}

可以使用類似的代碼插入列表的末尾,並在列表中的現有條目之前或之后插入稍有不同的代碼。

暫無
暫無

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

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