Linked Lists -- an introduction New problem: arrays are not - - PowerPoint PPT Presentation

linked lists an introduction
SMART_READER_LITE
LIVE PREVIEW

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-1
SLIDE 1

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.

slide-2
SLIDE 2

Assume (for simplicity) that the item to go into the list is an int. Start with an empty list. listadd(1) 1 listadd(2) 2 … 1 listadd(3) 3 … 2 … 1 listadd(4) 4 … 3 … 2 … 1

slide-3
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
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
SLIDE 5

struct node { int theint; struct node *next; };

slide-6
SLIDE 6

1 2 3 4 front Singly linked, but in the reverse order (add to end or back of the list)

slide-7
SLIDE 7

struct node { int theint; struct node *next; struct node *previous; };

1 2 3 4 front back Doubly linked

slide-8
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
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
SLIDE 10

int value = 1; Node *ptr; ptr = head; while (ptr != NULL) { ptr->theint = value * 11; value++; ptr = ptr->next; }

slide-11
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
SLIDE 12

With the correct code, what happens when this code is executed? ptr = three.next; ptr = ptr->next;