SLIDE 1
Linked Lists -- an introduction New problem: arrays are not - - PowerPoint PPT Presentation
Linked Lists -- an introduction New problem: arrays are not - - PowerPoint PPT Presentation
Linked Lists -- an introduction New problem: arrays are not dynamically sized. So, if a program cannot predict the size of a needed array, consider a linked list . Assume (for simplicity) that the item to go into the list is an int . Start with
SLIDE 2
SLIDE 3
“Knowing” where the next item in the list is is simple -- it is a pointer. We need to associate each item in the list with a pointer. 4 3 2 1
SLIDE 4
Set up a struct with 2 fields: int pointer to a struct (often called a node) After adding all 4 ints to the example list:
4 3 2 1
SLIDE 5
struct node { int theint; struct node *next; };
SLIDE 6
1 2 3 4 front Singly linked, but in the reverse order (add to end or back of the list)
SLIDE 7
struct node { int theint; struct node *next; struct node *previous; };
1 2 3 4 front back Doubly linked
SLIDE 8
For convenience, name this user-defined type: typedef struct node { int theint; struct node *next; } Node; Now, declarations have less (keyboard) typing: Node one, two, three; Node *head;
SLIDE 9
Some code, to show pointers and such. . .
- ne.theint = 1;
- ne.next = &two;
- ne.next->next = &three;
three.next = NULL; head = &one;
- ne
two three head
SLIDE 10
int value = 1; Node *ptr; ptr = head; while (ptr != NULL) { ptr->theint = value * 11; value++; ptr = ptr->next; }
SLIDE 11
int value = 1; Node *ptr; ptr = head; while (ptr != NULL) { ptr->theint = value * 11; value++; ptr = ptr.next; } Why is this now incorrect?
SLIDE 12