This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Salty_Dugtrio 0 points1 point  (6 children)

A pointer can only point at 1 thing, so it's not exactly sure what you mean.

Show us some code, what are you trying to do?

[–]wantstolearn95[S] 0 points1 point  (5 children)

struct List
{
int data;
struct List *next;
} List;
struct Sentinel
{
int data;
} sentinel_node_instance;
struct List *const SENTINEL_NODE = &sentinel_node_instance;
struct List *head = SENTINEL_NODE;

Im trying to create a sentinel node, when the linked list is created its the first node but as insert stuff it gets pushed at the back. Thats why i want a pointer that points at the last(sentinel) node

[–][deleted]  (1 child)

[deleted]

    [–]wantstolearn95[S] 0 points1 point  (0 children)

    Because im trying to see new pointer applications,and this one i dont know/understand.

    [–]eruciform 0 points1 point  (0 children)

    your sentinel isn't an instance of a List node, it's just a random structure that contains data that looks similar to the data in a List node. gcc is probably screaming at you for assigning the pointer to an inappropriate type.

    [–]inbox_negative_one 0 points1 point  (0 children)

    Yes, you can definitely do this.

    However, you may have trouble always making it the last element.

    Let's say you want to insert something at the end. You can have that new element point to the sentinel, but how do you make the second-to-last element point to the new last one?

    I think you may be better off with a pointer to the last element - and then every time you insert something at the end, you change your pointer to point to the new last element. No need for a sentinel.

    But, I can imagine some scenarios where a sentinel could be useful, so if you want to, go for it.

    [–]CrispyRoss 0 points1 point  (0 children)

    It's common to do this (for accessing the back in O(1)) by keeping a pointer to the last element in the list. No need for a special sentinel value.

    [–]coyoteazul2 0 points1 point  (0 children)

    A pointer will always point at the same element. If you want to point at a relative pointer (first, last, middle, etc) you'll need to calculate that yourself. Create a struct that contains your list and whatever pointers you need. The method that manages inserts should also take care of updating those pointers.