简体   繁体   English

C中链表的指针基础和顶部

[英]Pointer base and top for linked list in C

Data structure stack based on linked list has base and top pointers that 基于链表的数据结构堆栈具有基础指针和顶部指针
point to the members of the stack. 指向堆栈的成员。

struct node
{
     struct node* next;
     int val;
};
struct stack
{
    struct node* base;
    struct node* top;
}

So my question is can we use the same way to create a linked list, that way 所以我的问题是我们可以使用相同的方法来创建链接列表吗?
if we want to add new member to the rear of the list, we don't need 如果我们想将新成员添加到列表的末尾,则不需要
traverse the whole list. 遍历整个列表。

 struct listnode
    {
         struct listnode* next;
         int val;
    };
    struct linkedlist
    {
        struct listnode* base;
        struct listnode* top;
    }

Is this a appropriate? 这合适吗?

A pure stack would only need a top pointer. 堆栈仅需要顶部指针。 Maybe you are using that data structure as queue , adding at the end, taking from the beginning. 也许您正在使用该数据结构作为queue ,从头开始添加到末尾。

A linked list needs only a head , but for appending to the end a tail would be beneficial. 链表只需要一个 ,但对于追加到最后一个尾巴将是有益的。

struct linkedlist
{
    struct listnode* head;
    struct listnode* tail;
    int count; // Might be useful
}

(I used the conventional names.) (我使用了常规名称。)

One might mention the doubly linked list with: 可能有人会提到双重链表

struct node
{
     struct node* previous;
     struct node* next;
     int val;
};

Which would allow an entirely symmetric usage of head and tail. 这将允许头和尾的完全对称使用。

There's nothing to stop you creating a data structure with either of the pairs of structs that you have defined above. 没有什么可以阻止您使用上面定义的任意一对结构创建数据结构的。 However a linked list were you can add and remove elements at either the front or back without traversing the list is more like a dequeue a double ended queue. 但是,如果您可以在链表的前面或后面添加和删除元素而无需遍历该列表,则它更像是将双端列出 Similarly a stack were you can add or take elements from either end is also a tending towards being a dequeue. 类似地,您可以从任一端添加或获取元素的堆栈也趋向于出队。

What I think is happening is that you are getting confused between the formal interface and the underlying data structure. 我认为正在发生的事情是您在正式接口和基础数据结构之间感到困惑。 So if you created code with an API that allows elements to be added or removed from either end of a linked list of items that you can traverse and insert/remove from you can use that to present a stack or a linked list or a dequeue depending on which parts of the API you use and how you name them. 因此,如果您使用API​​创建代码,该API允许在您可以遍历并从中插入/删除的项目的链表的任一端添加或删除元素,则可以使用它来显示堆栈或链表或出队,具体取决于您使用API​​的哪些部分以及如何命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM