Question about singly linked lists

  • Thread starter AcecA
  • Start date
  • #1
AcecA
12
0
If you have a pointer that's pointing to one element in a list, can you do the following

(*biggestPtr-1).next := biggestPtr+1
?

This is pseudocode with := meaning the assignment operator.
 

Answers and Replies

  • #2
Filip Larsen
Gold Member
1,592
504
It looks like you are using something similar to C pointer notation and I guess you would like to remove an element pointed to by p from the list by doing "*(p-1).next = p+1". If so, note that pointer arithmetic is similar to using array index, that is, p-1 points to the element in memory prior to p and this is in general not the same as the element prior to p in the linked list.

In a single linked list where each element chain to the next, it is by definition not possible to find the element prior to an element directly from the element itself. You must maintain (or obtain by iteration from the head of the list) a pointer to the previous element separately and use that to unchain the element in question (with special care if the element to remove is the first element in the list).
 
  • #3
Bartleby50
33
0
i assume bigestPtr is the size of your list.
In this case the last Element of your list *(biggestPtr-1) points to an element that does not (yet) exist.
This is no problem if you always check .next >= biggestPtr.
And indeed the last element of the list cant have a valid next-pointer.
But a reference to *(biggestPtr.next) might give a runtime error now, or produce random results.
If biggestPtr is not the size of the list, but points to any other element. you have set (*biggestPtr-1).next to the next element in memory, which is not necessarily the next logical element of the list.
 
Last edited:

Suggested for: Question about singly linked lists

  • Last Post
Replies
0
Views
218
  • Last Post
Replies
9
Views
1K
  • Last Post
Replies
4
Views
506
  • Last Post
Replies
15
Views
1K
  • Last Post
2
Replies
66
Views
2K
  • Last Post
2
Replies
40
Views
1K
  • Last Post
Replies
18
Views
1K
  • Last Post
Replies
31
Views
1K
  • Last Post
2
Replies
57
Views
2K
Top