aps105 lists. structures arrays allow a collection of elements –all of the same type how to...
TRANSCRIPT
APS105
Lists
Structures
Structures
• Arrays allow a collection of elements– All of the same type
• How to collect elements of different types?– Structures; in C: struct
• General form:
struct { <variable declarations> } <identifier list>;
Example• A struct of stock items at a store:
.
Separate Definition from Declaration
.
Using Typedef
• Can define your own types using typedef!• General form:
typedef <type> <yourTypeName>;• Examples:
.
Doing typedef and definition at once:
.
Referencing Struct Members
.
Structs and Pointers
StockItem x;StockItem *p;p = &x; // p points to x
// ways to set quantity to 500:.
Malloc a Struct (StockItem)
.
Lists
Intro
• A list is a sequence of items– can implement lists different ways:
• a group of variables• an array• using pointers (as we will see)
• Typical list operations– start a new, empty list– insert a new element into the list– find an item with a certain value in the list– delete an item from the list– print the list
• Abstract Data Type (ADT)– A list is an example of an ADT– An ADT is a concept– there are multiple ways to implement an ADT
The Problem with Arrays
• Insert an item into the middle of the list:
• Delete an item from the middle of the list:
• What if the array isn’t big enough?
5 3 1 6 2 6 7 0
9
5 3 1 6 2 6 7 0
X
5 3 1 6 2 6 7 3 8 0
9
Flexible List: “Linked List”
• Insert an item into the middle of the list:
• Delete an item from the middle of the list:
9
5 3 1 6 2 6 7
5 3 1 6 2 6 7
X
5 3 1 6 2 6 7
Implementing a Linked List of ints
.
Allocating a new Node
• a function to allocate & initialize a node
.
Creating a List: Adding to the end
.
Creating a List: Adding to the front
.
Function to Print a List
.
Deleting the First Node of a List
info: 5link:
myListinfo: 3link:
info: 1link:
Function to Delete first Node
.
Delete first Node: return new head
.
Function to return true if an item found
.
Function to Delete Entire List
.
Function to Add Element to End of List
.
Deleting the Last Node of a List
info: 5link:
myListinfo: 3link:
info: 1link:
Function to Delete Last Element
.
Inserting into an Ordered List
info: 1link:
myListinfo: 3link:
info: 5link:
4
Function to Insert into Ordered List.
Using Recursion on Lists
Printing a List using Recursion• can think of a list recursively as: a head node plus a list
.
Deleting a List using Recursion.
Finding an Item using Recursion.
Compare 2 Lists: true if identical.
Insert into an Ordered List.