linked lists - github pages · create a singe node linked list ml node nti m1 n1 data 10s data nest...

Post on 26-Mar-2020

28 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

LINKED LISTSProblem Solving with Computers-I

Store a sequence of numbers or

names or snacks or anydata

1 Array Fixed size

int arr 100J 11 Only storea 100 numbers

2 Linked list Variable size

Main difference comparedto aways

Elements are not next to each

other in memory

arr T B Nggde

0 8000 0 8004 0 8008

edqtaAddress of the

next boogie

did FEDhead Node

RepresentinganodestructNode

int dataNodes next

o

3

Create a singe node linked listMl

Node nti M 1n1 data 10 s data nestmi next 2 O's

Node25 nim2 dates w

n2 next 0Addressofthe nett

nodedata next

t.TOhead next 0 7,000400

ml next h2

n1 data 50

Node head

Print the data of both nodes using

thevariableheadcouta head data

head 2 next r

T.gscout Ls head data

cont Cs headnext data

cont CC head next next

outschead next next da

Accessing elements of a linked list

Assume the linked list has already been created, what do the following expressions evaluate to?1. head->data2. head->next->data3. head->next->next->data4. head->next->next->next->data

A. 1B. 2C. 3D. NULLE. Run time error

head

struct Node {int data;Node *next;

};

is weeDaerneffgg

Seg fare

Creating a small list3

• Define an empty list• Add a node to the list with data = 10

struct Node {int data;Node* next;

};

Heap vs. stack

Node* createSmallLinkedList(int x, int y){Node* head = NULL;Node n1 ={x, NULL};Node n2 ={y, NULL};head = &n1;n1->next = &n2;return head;

}

Does the above function correctly return a two-node linked list?A. YesB. No

n Steed nzstad

Node pM 12211

pecreat Io 20 P

The nodes are removed fromthe stack

after the functionreturns

Stackhead Do empty

Heap value

Case I data next

n to li ID

case 2 Before calling insertNode

Heap head Heap

notE g

After calling insert Node

p

Creating a small list5

• Define an empty list

• Add a node to the list with data = 10

struct Node {int data;Node* next;

};

struct LinkedList {Node* head;Node* tail;

};

Inserting a node in a linked listvoid insert(LinkedList* h, int value) ;

Iterating through the listint count(LinkedList* list) {

/* Find the number of elements in the list */

}

head tail

list

Deleting the listint freeList(LinkedList * list) {

/* Free all the memory that was created on the heap*/

}

head tail

list

Next time• Memory-related errors• Double-linked lists

top related