PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Linked Lists

Im finally working on my first commercial product for the ppc. Im writing PocketPad a note pad replacement that will blow pockentoepad away im going to put some really good features in that i think pocket notepad should have but is missing, im probably only gonna sell it fo 10 dollars or something cheap. My question is what are linked lists usefull for? I dont know if i need to use them or not for anything but can someone tell me what there commonly used for or could be used for. And what there advantages and disadvantages are as far as speed and such.
refractor · 31 Jan 2002, 09:24 UTC — Linked lists..
A linked list is one of the most fundamental algorithms out there. The question sounds like homework I did when I was 16 :wink:

Basically it's what is says it is. It's a set of objects/structures which are linked together to form a chain.

You store:
a pointer to the first object

Then:
each object points to the next object in the chain

And:
the last object's pointer is NULL.


The advantage is that you can create/delete your structures and tag them onto/take them off of the linked list relatively easily. You don't have to pre-declare how much memory you're going to need (like an array), because you can add items as you wish.

A doubly-linked list allows you to move forwards AND backwards along the chain of objects.

Properties:
the list is easy to traverse.
inserting into a (unsorted) list has a constant penalty O(1)
deleting an item is O(N)

Get yourself a book on "algorithms". 8O

Linked lists aren't the way to go on a processor like a StrongARM if you *really* want flat-out speed (because while you're traversing the list the processor fills a cache line with stuff you're not going to use)...

Cheers,

Refractor.
hmm... well all i kow about them is for stuff like this:

starting at n = 2...

n data pointer
1 o -1
2 h 4
3 l 5
4 e 3
5 l 1

spells out: h e l l o

it kinda goes all over the place by each data item being linked to the next. i think thats how it works anyway. i guess you'd set up an array to make one... dunno what you'd use it for though
ah crap, beat me to it... well, you can see my demonstration anyway.
MirekCz · 31 Jan 2002, 10:14 UTC — I love linked lists;)
linked lists are totally awesome:) For example in a map editor where you don't know how many bitmaps user will load. You simple store bitmaps in a linked list and this way you keep track of them. Now if user wants to add another bitmap you just check if it was previously loaded (for ex. go thru the linked list with filename) and you either return a pointer to the bitmap, if it was found loaded, or load it, add it to the linked list and return the new pointer you just created. Simple and quite effective:)
And about linked lists lieing around memory... there are ways to prevent it. For example you can set an array of 100 linked lists structures everytime. Now you fill this structure as new nodes are added. And eventually, if you reach more then 100 nodes you add another 100 structures array. This way your linked lists are arranged quite linearly. The only drawback is that deleting a single linked list might give you problems. Althrought it can be easily solved with a boolean active/deactive flag for every linked list and traversing the linked list for "empty" structures everytime you add a new node.
Well see learning to code them isnt a real big deal i just want dont quite see i use for them, well i didnt see a use for them. But now that i know that stuff about them veing like a dybamic array of structures it seams very usefull.
Another huge advantage of linked lists is that they can be split, merged and inserted into one another very, very easily compared to arrays. One of the main uses for linked lists is for storing elements of an unknown number. They are also extrememely useful for queues, where you pop items off the head of the list.

Dan East
You might want to pick up a book on algorithms or data structures before you start coding. Sedgewick's "Algorithms in C" is a good one, but a bit dated. Other folks here could probably recommend something a bit more recent.
Does anyone else recommend not using them for a ppc app as suggested above, howw much cache are we really looking at a linked list eating up if its only about 100 items or so?
Don't worry about it. In your case you'll probably never see a problem. In the odd chance that you do, profile your list traversal routine then come back and give us your profiling numbers. I'll be happy to help you at that point.

Chunking, or allocating blocks of nodes at one time (as Mirek suggested) is one way to minimize cache thrashing. There are other ways, but rather than getting into it now, come back once you know that your list operations are the bottleneck in your app.
RwGast wrote:
Does anyone else recommend not using them for a ppc app as suggested above, howw much cache are we really looking at a linked list eating up if its only about 100 items or so?


I'm going way back in time here, so someone else can correct me if I'm way off. :wink:

The way refractor was describing, each object stored a pointer to the next in the list. So as you traverse the list, you're loading each object to get the pointer to the next object.

But, another way to do it is to create a linked-list of pointers. So instead of having each object point to the next, you simply have a list of pointers to objects. Did that make sense?

Pam
Yeh, but that's just simply overkill unless you are going to sort the double list.
now, if you would kindly give us some information on these features...!
Pam,

That method doesn't buy you much because when you typically traverse a linked list you need to look at the data in each node. That means you'll not only have to touch the memory of your list of pointers, but you'll have to dereference the pointer to get at the data in the node. Did I miss something?
Uh oh, Pam. If Paul sees you talking about programming it's all over :D
andys · 01 Feb 2002, 01:05 UTC — I love linked lists;)
MirekCz wrote:
The only drawback is that deleting a single linked list might give you problems. Althrought it can be easily solved with a boolean active/deactive flag for every linked list and traversing the linked list for "empty" structures everytime you add a new node.


you can just have a seperate linked list called "empty" - and pull nodes off of that. Removing items from a linked list is quick - especially if it's doubly linked (although that has other penalties).

This can be better than calling malloc frequently.
If all of the items in the list are the same size, and you know you aren't trying to delete the last item in the list (or you have a circular list), then removing an item from a singly-linked list can be performed by a simple memcpy.

You copy the entire contents of the next item in the list to the current item, then you delete the next item (or move it to the "free" list).

Here's a singly-linked list with 4 items:

A->B->C->D

If you want to delete item B, you copy C (incl. C's pNext pointer) to B, then delete C. Since C's pNext pointer pointed to D, after the copy, C's pNext pointer now points to D. Pretty slick, eh?
refractor · 01 Feb 2002, 10:46 UTC — More linked lists :-)
Hello.

Just thought I'd clear some things up (mainly regarding the cache hit issue I mentioned).

Firstly, for a majority of cases, the speed loss of a regular linked-list *really* isn't going to matter. If you're writing a text editor or whatever, then a few cache misses aren't going to matter a great deal... if, however, you're writing a game or something that *needs* speed, then it's more of a problem.

Regarding Pam's question, Digby's reply is correct. A list of pointers into the data doesn't really help all that much - you're just increasing the chances that the next pointer to the next data is in the cache... but the data you *need* from the object may not be - there's no point looking up a pointer if you always have to use some of the object to figure out if it's the one you want.

To best organise the linked list on a processor, you want to put all of the data used in your traversal comparison into the cache-line width of that processor, and align data to a cache-line boundary.

So, on the StrongARM, for example, has a 32-byte cache line width.

If I request a single byte of data, 32-bytes will be requested and loaded into the cache (if it's in a cacheable area - let's pretend it is :lol: ).

If my object is, say, 64- bytes long, structured like this:

long l_my_id
char c_filler[56]
pointer p_next

And my (nasty pseudo) code goes:

obj = head_object

// we want to find object 63
while obj.l_my_id <> 63 and obj.p_next!=null
obj = boj.p_next
loop

First the processor will load the first 32-bytes of the object (to read l_my_id)... then it'll read the next 32-bytes to read the p_next.

If I reorganise my data *slightly*:
long l_my_id
pointer p_next
char c_filler[56]

... then I'm only ever going to bother loading *one* cache line per object for the traversal. This means I load 1/2 as much data, which increases the chances of things hitting the cache.

You could also store the "traversal" data (the pointer and the items used in the comparison) in one area along with a pointer to the data you rarely use.

Sometimes optimisation is more about thinking about clever data placement rather than making the code itself faster :-)

MirekCz is correct too, if you're allocating data using malloc for each small structure, you're going to suffer from memory fragmentation, and nasty speed issues. If you allocate a block of memory (say 64 at a time), then you can just use that as a set of empty links. When you want to add an object, you simply pick the next new object in your array. When they're all used, allocate another block. That means you only hit the malloc() function once every 64 objects.

Cheers,

Refractor.
Ok, yeah you're right. You would still have to dereference the pointer to see if you had found what you were looking for.

Unless...

Well, it depends what's being stored in the linked list and what is being done with the data. Let's take an academic example and say you're storing student records; studentID, Name, Phone, Address, GPA, Major, etc. Possibly a lot of data, but when you are traversing the list in a search, you only need to check the ID field. So if you create a list of pointers to student records and only store the ID in the list, then you can traverse the list quickly without loading each record into memory. This method was used a lot in the past, imagine only having 64K of RAM but a Terabyte of data on slow tape-drives. Loading the entire object just to see if you found the right one was too inefficient.

On the other hand, if you are traversing the list to process the data, like printing out the student records, then this method is actually slower (a little).

Also, if you are going to search to random elements in the list often and the list is going to be big, there are much better data structures. Binary Trees for example.

Anyway, someone else suggested before picking up a book on algorithms or data structures. That's really the best thing to do. Study several, learn a few, master a couple and use the one appropriate for your situation.


Pam
Pam wrote:
Ok, yeah you're right. You would still have to dereference the pointer to see if you had found what you were looking for.

Unless...

Well, it depends what's being stored in the linked list and what is being done with the data. Let's take an academic example and say you're storing student records; studentID, Name, Phone, Address, GPA, Major, etc. Possibly a lot of data, but when you are traversing the list in a search, you only need to check the ID field. So if you create a list of pointers to student records and only store the ID in the list, then you can traverse the list quickly without loading each record into memory. This method was used a lot in the past, imagine only having 64K of RAM but a Terabyte of data on slow tape-drives. Loading the entire object just to see if you found the right one was too inefficient.


Surely this is just an indexed data structure? You could implement this for almost anything. You might indeed use a linked list in the background and use an approach like this to index into it. It makes some things more expensive, but can make other things cheaper.
Thank you guys for making me realize i dunno shit about this stuff. It helped me relize the right way to acually go about this was to read an algorithm book so i orderd and oreilly book on the topic. Now i really suck at bit operations and i get the feeling im going to need to learn this stuff before i can delve into algorithms. I mean ive read many chapters on it but i still dont get like when i see code always using | to merge flags a would think that would be &. Anyway can someone reccomend a good article on this subject?
Boolean operations are simple - you just have to think in binary.

let's say you have a 8bit binary number - 00000000 (ie, 0)

Now, you want to use this to hold flags. You would define each one of these bits as being a flag. ie - 1,2,4,8,16,32,64,128

this leads to
#define FLAGA 0x01
#define FLAGB 0x02
#define FLAGC 0x04
#define FLAGD 0x08
#define FLAGE 0x10

etc

the 0x prior to the number tells the system to treat it as hex - which is why FLAGE is 10 and not 16 - 10 being 16 in hex.

Now. A processor has a stack of functions to deal with bits - it has AND, OR, NOT and XOR (you can use combinations to simulate others)

now
OR says - if a bit is set in mask 1, or in mask 2 (or both) then set it in the final output.

So - you would do myMask = myMask | FLAGE
- so as to say - if FLAGE is set in myMask, then nothing will happen - otherwise, because it's set in FLAGE - the final combination will be myMask and FLAGE.

To check for a flag (or to eliminate all flags except one) you use AND
if(myMask & FLAGE) {.....}

- AND says "only produce bits that are in mask 1 and mask 2". In this case - if FLAGE is set then the AND will produce a non-zero number (which in C/C++ is the same as true)

NOT basically toggles them - if a bit is set then it is unset, otherwise it is set. This is acomplished by using ~ in C.

XOR is "Exclusive OR" - this says set a bit in the output if it is set in the first mask, or the second mask, but not if it is set in both.

XOR is a fundamental basis for encryption algorithms (indeed, SCUMM games for example are generally "encrypted" by a single byte XOR. You can repeat the XOR to "decrypt" the data.

You may also want to use combinations of this. For example - if you want to switch off a flag you might use a combination of NOT and AND - for example

myMask &= ~FLAGE
~FLAGE is every flag *except* e - and so the final output will contain every flag already in myMask, except for E.

Hope this helps.
Thank you very much guys finally after all this damned time i have figure it out! Anyways i was wondering what is the advantage of using this style instead of texting an int for 1 or 0 sure it can store up to eight flags but it takes longer to test all 8 bits for one flag doesnt it?
Code:

#include <stdio.h>
#define FLAG_A 0x01

main()
{
char var;
var = 'a';

var = var | FLAG_A;
printf("%s", var);
}


why would this cause the dos prompt to crash? Is it becuase the byte with the flag ored into it maybe genrating a number above the acii table or something?
What i just said cant be right becuase oring those values cant generate a number higher than 256 and the extended ascii table goes to 256 am i right?
It's crashing because you've told printf that you're supplying a null-terminated string, when in fact you're supplying a single character.
heh, that was a really stupid ass mistake im sorry. But what about the advantages of using bit comparison over single varible checks? Is it just to make it easyer to pass multiple option to your function this way, i mean is ease the only advantage not speed?
RwGast:about keeping flags in an int.. first of all, int is 32bpp, so you can keep 32flags per int.
And here are advantages/disadvanteges as I see them:
1.checking if a flag is set is pretty simple and doesn't really take much more time
2.you need much less memory(good for larger arrays)
3.reading is actually faster if you read few flags from one int and/or if your cpu stores them in cache(which is much harder without flags because cache gets trashed with mostly empty values and it's also harder to find a value you want to check next in cache)
4.it saves a lot of space in files if you use it
5.you can store a mixed data in such an int, for example 4*4bits numbers+16flags, great for making maps etc which take really little mem.
6.and yeah, m$ uses it;P

hope it helps you find a good use for it:)