简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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