c programming lecture 25 self-referential structures linked lists

19
C Programming C Programming Lecture 25 Lecture 25 Self-Referential Self-Referential Structures Structures Linked Lists Linked Lists

Upload: monica-nichols

Post on 11-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming Lecture 25 Self-Referential Structures Linked Lists

C ProgrammingC Programming

Lecture 25Lecture 25Self-Referential Self-Referential

StructuresStructuresLinked ListsLinked Lists

Page 2: C Programming Lecture 25 Self-Referential Structures Linked Lists

Self-Referential StructuresSelf-Referential Structures

Self-referential structures have Self-referential structures have pointer memberspointer members that hold the that hold the address of the same structure address of the same structure type.type.• The pointer members allow the linking The pointer members allow the linking together of an unspecified number of together of an unspecified number of such structures.such structures.

• Example:Example:struct list {struct list {

int data;int data; struct list struct list *next*next;; };};

Page 3: C Programming Lecture 25 Self-Referential Structures Linked Lists

Pictorial RepresentationPictorial Representation

To help us understand and think To help us understand and think about self-referential about self-referential structures, we use pictures:structures, we use pictures:

datadata nextnext

The dataThe datamembers.members.

The pointerThe pointermember.member.

Page 4: C Programming Lecture 25 Self-Referential Structures Linked Lists

An ExampleAn Example

struct list {struct list { int data;int data; struct list *next;struct list *next;

}}

struct list a, b, c;struct list a, b, c;a.data = 1; a.data = 1; The result of theseThe result of theseb.data = 2; b.data = 2; declarations anddeclarations and c.data = 3; c.data = 3; initializations is picturedinitializations is pictured

below:below:a.next = b.next = c.next = NULL;a.next = b.next = c.next = NULL;

aa bb cc11 22 33NULLNULL NULLNULL NULLNULL

Page 5: C Programming Lecture 25 Self-Referential Structures Linked Lists

Continuation of ExampleContinuation of Example

a.next = &b;a.next = &b;

b.next = &c;b.next = &c;

aa bb cc11 22 33 NULLNULL

Now we can use the links to retrieveNow we can use the links to retrievedata from successive elements.data from successive elements.

a.next->dataa.next->data has a value ofhas a value of 22a.next->next->dataa.next->next->data has a value ofhas a value of 33

Page 6: C Programming Lecture 25 Self-Referential Structures Linked Lists

Linear Linked ListsLinear Linked Lists

A linked list has a A linked list has a head pointerhead pointer that addresses the first element that addresses the first element of the list.of the list.• Then the Then the pointer memberpointer member in each in each structure in the list structure in the list points to a points to a successor structuresuccessor structure..

• The The last structurelast structure has its has its pointer pointer membermember set to set to NULLNULL..

Typically, a linked list is Typically, a linked list is created created dynamicallydynamically..

Page 7: C Programming Lecture 25 Self-Referential Structures Linked Lists

Dynamic Storage Dynamic Storage AllocationAllocation

““Dynamic” storage allocation Dynamic” storage allocation refers to allocation of storage refers to allocation of storage during program execution time, during program execution time, rather than during compile time.rather than during compile time.• Utility functions such as Utility functions such as malloc()malloc() are provided in the standard library are provided in the standard library to allocate storage dynamically.to allocate storage dynamically.– mallocmalloc()stands for “()stands for “mmemory emory allocallocation”. ation”.

Page 8: C Programming Lecture 25 Self-Referential Structures Linked Lists

Header File for Example of Header File for Example of Dynamic Creation of a Linked Dynamic Creation of a Linked

ListList

#include <stdio.h>#include <stdio.h>

typedef char DATA; typedef char DATA; /* use char in examples *//* use char in examples */

struct linked_list {struct linked_list {

DATA d;DATA d;

struct linked_list *next;struct linked_list *next;

};};

typedef typedef struct linked_liststruct linked_list ELEMENTELEMENT;;

typedef typedef ELEMENT *ELEMENT * LINKLINK;;

Page 9: C Programming Lecture 25 Self-Referential Structures Linked Lists

Example of Example of Dynamic Allocation of a Dynamic Allocation of a

Linked ListLinked Listhead = malloc(sizeof(ELEMENT));head = malloc(sizeof(ELEMENT));head->d = ‘n’;head->d = ‘n’;head->next = NULL;head->next = NULL; headhead nn NULLNULL

head->next = malloc(sizeof(ELEMENT));head->next = malloc(sizeof(ELEMENT));head->next->d = ‘e’;head->next->d = ‘e’;head->next->next = NULL;head->next->next = NULL;

headhead nn ee NULLNULL

head->next->next = malloc(sizeof(ELEMENT));head->next->next = malloc(sizeof(ELEMENT));head->next->next->d = ‘w’;head->next->next->d = ‘w’;head->next->next->next = NULL;head->next->next->next = NULL;

headhead nn ee ww NULLNULL

Page 10: C Programming Lecture 25 Self-Referential Structures Linked Lists

List OperationsList Operations

Basic List OperationsBasic List Operations• Creating a listCreating a list• Counting the elementsCounting the elements• Looking up an elementLooking up an element• Inserting an elementInserting an element• Deleting an elementDeleting an element

Page 11: C Programming Lecture 25 Self-Referential Structures Linked Lists

Creating a List Creating a List from a String using Recursionfrom a String using Recursion

#include “list.h”#include “list.h”

LINK LINK string_to_liststring_to_list((char s[]char s[])){{ LINK head;LINK head; if (s[0] == ‘\0’) /* base case */if (s[0] == ‘\0’) /* base case */ return NULL;return NULL; else {else { head = malloc(sizeof(ELEMENT));head = malloc(sizeof(ELEMENT)); head->d = s[0];head->d = s[0]; head->next = head->next = string_to_liststring_to_list((s + 1s + 1);); return head;return head; }}}}/* We will walk through this in class for the string “hello” *//* We will walk through this in class for the string “hello” */

Page 12: C Programming Lecture 25 Self-Referential Structures Linked Lists

Counting the Elements in Counting the Elements in a Lista List

/* Count the elements recursively *//* Count the elements recursively */

#include “list.h”#include “list.h”

int int countcount((LINK headLINK head)){{ if (head == NULL)if (head == NULL) return 0;return 0; elseelse return(1 + return(1 + countcount((head->nexthead->next));));}}

Page 13: C Programming Lecture 25 Self-Referential Structures Linked Lists

Lookup Lookup cc in the List Pointed to in the List Pointed to by by headhead

#include “list.h”#include “list.h”

LINK LINK lookuplookup((DATA c, LINK headDATA c, LINK head)){{ if (head == NULL)if (head == NULL) return NULL;return NULL; else if (c == head->d)else if (c == head->d) return head;return head; elseelse return(return(lookuplookup((c, head->nextc, head->next));));}}

Page 14: C Programming Lecture 25 Self-Referential Structures Linked Lists

Illustration of Illustration of InsertionInsertion of a New List Elementof a New List Element

Before insertion:Before insertion:

AA CC

BB NULLNULL

. . .. . .

qq

After insertion:After insertion:

AA CC

BB

. . .. . .

qq

Page 15: C Programming Lecture 25 Self-Referential Structures Linked Lists

Recursive Function to Recursive Function to Insert an Element in a ListInsert an Element in a List

#include “list.h”#include “list.h”

void insert(LINK p1, LINK p2, LINK q)void insert(LINK p1, LINK p2, LINK q){{ p1->next = q; /* insertion */p1->next = q; /* insertion */ q->next = p2;q->next = p2;}}

AA CC

BB

. . .. . .

qq

p1p1 p2p2

Page 16: C Programming Lecture 25 Self-Referential Structures Linked Lists

Deleting an Element from a Deleting an Element from a ListList

p->next = q->next; p->next = q->next;

AA CCBB . . .. . .

pp qq

p->next priorp->next priorto delete.to delete. p->next afterp->next after

the delete.the delete.

Note that the deleted node is now garbage (of noNote that the deleted node is now garbage (of nouse). Its storage can be returned to the systemuse). Its storage can be returned to the systemby using the standard library function by using the standard library function free()free()..

Page 17: C Programming Lecture 25 Self-Referential Structures Linked Lists

Recursive Deletion of a Recursive Deletion of a ListList

/* Recursive deletion of a /* Recursive deletion of a listlist. */. */

#include “list.h”#include “list.h”

void void delete_listdelete_list((LINK headLINK head)){{ if (head != NULL) {if (head != NULL) { delete_listdelete_list((head->nexthead->next);); free(head); /* release storage */free(head); /* release storage */ }}}}

Page 18: C Programming Lecture 25 Self-Referential Structures Linked Lists

Demonstration StructuresDemonstration Structuresstruct date_rec { int month; int day; int year;}; /* year is stored as yyyy */

struct friend_rec { char fname[15]; /* assume first name is stored in caps */ char phone[9]; /* local number only, such as 555-1234 */ struct date_rec birthday;};

struct my_friends { struct friend_rec a_friend; struct my_friends *next;};. . .struct date_rec dob;struct friend_rec friend;struct my_friends *head, *current, *new;

Page 19: C Programming Lecture 25 Self-Referential Structures Linked Lists

Direct Input/OutputDirect Input/Output

The functions The functions fread()fread() and and fwrite()fwrite() are used to read and are used to read and write write binarybinary files. files.• No conversions are performed as No conversions are performed as they are with fscanf().they are with fscanf().

• In certain applications (those In certain applications (those that use structures), the use of that use structures), the use of these functions can save these functions can save considerable time.considerable time.– Because one fread or fwrite can Because one fread or fwrite can input or output an input or output an entire entire structurestructure..