accessing linked list members

How can linked list members be accessed? so far I've got this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"

struct Slinked_list
{
	int iVar;
	char * s;
	Slinked_list * next;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Slinked_list * e; e->next = NULL; 
	Slinked_list * d; d->next = e;
	Slinked_list * c; c->next = d;
	Slinked_list * b; b->next = c;
	Slinked_list * a; a->next = b;
//find out about accessing a linked list


	return 0;
}

You never create an actual Slinked_list object there ( only some pointers )
how about this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Linked Lists.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Slinked_list
{
	int iVar;
	char * s;
	Slinked_list * next;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Slinked_list  e; e.next = NULL; 
	Slinked_list  d; d.next = &e;
	Slinked_list  c; c.next = &d;
	Slinked_list  b; b.next = &c;
	Slinked_list  a; a.next = &b;
//find out about accessing a linked list

	return 0;
}
How could I access d without knowing its d, lets just say I just wanted to access the 4th element, how could I do it?
Usually list nodes are created dynamically.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Slinked_list * list;

// creating list
Slinked_list *node = list;
for ( int i = 0; i < 8; i++ )
   node->next =  new Slinked_list; // You'll have to call delete in a similar way to free the memory
node->next = NULL; // last one

// accessing nth element
Slinked_list *t = list;
for ( int i = 0; i < n; i++ )
{
    if ( t == NULL )
       // there's no nth element
}
if ( did not find NULL )
   t is the nth element  
closed account (D80DSL3A)
Consider a to be element 0, then d is element 3.
1
2
3
4
5
6
7
8
9
10
11
12
Slinked_list* iter = &a// so its pointing to the "head" of the list
for(int i=0; i<3; i++)
    if( iter->next )
        iter = iter->next;
    else
    {
        cout << "Oops! There are less than 4 nodes in the list.";
        break;
    }

if( iter )// it got to the 4th element
    cout << "The value of iVar in the 4th node = " << iter->iVar;

Your use of automatic variables for nodes should work though it's unconventional.
Topic archived. No new replies allowed.