Docsity

Linked Lists - Data Structures and Algorithm - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Linked Lists - Data Structures and Algorithm - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures &

Algorithm Analysis

Linked Lists

โ€ข Avoid the drawbacks of fixed size arrays with

โ€“ Growable arrays

โ€“ Linked lists

Tight Strategy

โ€ข Add a number k (k = constant) of elements

every time the capacity is exceeded

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15

C0 + (C0+k) + โ€ฆ (C0+Sk) = S = (N โ€“ C0) / k Running time? C0 * S + S*(S+1) / 2 ๏ƒ  O(N^2 )

Tight Strategy

void insertLast(int rear, element o) {

if ( size == rear) {

capacity += k;

element* B = new element[capacity];

for(int i=0; i<size; i++) {

B[i] = A[i];

A = B;

A[rear] = o;

rear++;

size++; }

Linked Lists

โ€ข Avoid the drawbacks of fixed size arrays with

โ€“ Growable arrays

โ€“ Linked lists

Using Dynamically

Allocated Memory (review)

int i, *pi;

float f, *pf;

pi = (int *) malloc(sizeof(int));

pf = (float *) malloc (sizeof(float));

*pi =1024;

*pf =3.14;

printf(โ€an integer = %d, a float = %f\nโ€, *pi, *pf);

free(pi);

free(pf);

request memory

return memory

bat ๏‚Ÿ cat ๏‚Ÿ sat ๏‚Ÿ vat NULL

mat ๏‚Ÿ

Insertion

Compare this with the insertion in arrays!

bat ๏‚Ÿ cat ๏‚Ÿ mat ๏‚Ÿ sat ๏‚Ÿ vat NULL

dangling reference

Deletion

typedef struct node, *pnode; typedef struct node { char data [4]; pnode next; }; Creation pnode ptr =NULL; Testing #define IS_EMPTY(ptr) (!(ptr)) Allocation ptr=(pnode) malloc (sizeof(node));

Declaration

Implementation

๏‚Ÿ b a t \0 NULL

address of first node

ptr data ptr^ link

ptr

e ๏ƒ  name ๏ƒฐ (*e).name

strcpy(ptr ๏ƒ  data, โ€œbatโ€);

ptr ๏ƒ  link = NULL;

Create one Node

void insertAfter(pnode node, char* data) { /* insert a new node with data into the list ptr after node */ pnode temp; temp = (pnode) malloc(sizeof(node)); if (IS_FULL(temp)){ fprintf(stderr, โ€œThe memory is full\nโ€); exit (1); }

Insert (after a specific position)

strcpy(temp->data, data); if (node) { noempty list temp->next=node->next; node->next= temp; } else { empty list temp->next= NULL; node =temp; } }

10 ๏‚Ÿ 20 NULL

temp

node

void removeAfter(pnode node) { /* delete what follows after node in the list */ pnode tmp; if (node) { tmp = node -> next; node->next = node->next->next; free(tmp); } }

10 ๏‚Ÿ 50 ๏‚Ÿ 20 NULL

10 ๏‚Ÿ^20 NULL

node

void traverseList(pnode ptr) { printf(โ€œThe list contains: โ€œ); for ( ; ptr; ptr = ptr->next) printf(โ€œ%4dโ€, ptr->data); printf(โ€œ\nโ€); }

Traverse a list

Where does ptr point after this function call?