First post, by vgagame
Can someone show me how I could access the link pointer of any node in a linked list? My linked list is implemented with a struct that contains a pointer to the next structure or next node in the linked list. If I have several nodes, each having a link to the structure that comes next in the list, how could I access the pointer to the next structure for any node in the linked list? I am interested in the process of inserting a node into the list. The insert function first creates a new node and a character input by the user is saved in the node. If it is the first node in the list the pointer the next node is NULL. For each succesive node the pointer contains an address to the next node. If for example I had 4 nodes linked, each having the address of the next node after it, how could I access or otherwise use a debugger or printf to "see" the pointer of say the second or the first node if I just created the last node? What is happening in my insert function malloc is used to create a new node and there is a pointer to NULL for the first node and the address of the next node for the nodes following the first. Once I several nodes have been created I would like a way to findout what the contents of the pointer is of an earlier node stored in memory. I can use a debugger to see pointers of nodes that are currently being established. But not nodes that were already created.
// self-referential structure
struct listNode {
char data; // each listNode contains a character
struct listNode *nextPtr; // pointer to next node
};
typedef struct listNode ListNode; // synonym for struct listNode
typedef ListNode *ListNodePtr; // synonym for ListNode*
...
// insert a new value into the list in sorted order
void insert(ListNodePtr *sPtr, char value) {
ListNodePtr newPtr = malloc(sizeof(ListNode)); // create node
if (newPtr != NULL) { // is space available?
newPtr->data = value; // place value in node
newPtr->nextPtr = NULL; // node does not link to another node
ListNodePtr previousPtr = NULL;
ListNodePtr currentPtr = *sPtr;
// loop to find the correct location in the list
while (currentPtr != NULL && value > currentPtr->data) {
previousPtr = currentPtr; // walk to ...
currentPtr = currentPtr->nextPtr; // ... next node
}
// insert new node at beginning of list
if (previousPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else { // insert new node between previousPtr and currentPtr
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else {
printf("%c not inserted. No memory available.\n", value);
}
}