Вы находитесь на странице: 1из 21

LINKED LISTS

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Value v. Reference
Stack

int x = 10; int *xptr = &x;


int *yptr = new int; *yptr = x; delete yptr;

... 100 96 92 ... Heap ... 12 8 4 ... 10 x: 10 xptr: 0x100 yptr: 0x12

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Pointers
Data types are classified as
Value: variable holds actual value Reference: variable holds a reference (address) to the actual value

Pointers are reference data types


int x = 10; int *p = &x; *p = 20; // p refers to x (static allocation) // change x to 20

int *p1 = new int; *p1 = 100;

// p1 refers to an allocated int (dynamic allocation) // assign 100 to allocated int

delete p1;
p1 = NULL;

// deallocate memory held by int


// p1 refers to nothing

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Pointers
Dynamic memory is allocated on the heap using new
Must be deallocated, using delete
int *p = new int [100]; p[0] = 1; delete [] p; // p refers to an array of ints // first element is assigned the value 1 // delete the allocated array

struct Box { int len, width; }; Box *b = new Box; b->len = 10; delete b; b = NULL;

// struct definition

// b refers to an allocated struct // len member is set to 10 // memory deallocated

-> operator allows access to struct|class members through pointer

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Pointers
Multi-dimensional pointers
int** mat = new int* [3]; // 3 element array of pointers to int

for (int i = 0; i < 3; i++) { mat[i] = new int[4]; } // allocate an array of 4 ints

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

for (int j = 0; j < 4; j++) {


mat[i][j] = 0; } } // set each element to 0

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Linked List


Display
Node* iter = head; while (iter != NULL) { cout << iter->item << endl; iter = iter->next; } // item is the data portion // next is the link portion // iter refers to the first node

Delete
head = head->next; before->next = after; // remove first node // remove other node

delete del; del = NULL;

// delete memory

Insert
head = new Node(item, head); // insert at the front

before->next = new Node(item, after);

// insert elsewhere

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Linked List Head Node


Display
Node* iter = head->next; while (iter != NULL) { cout << iter->item << endl; iter = iter->next; } // item is the data portion // next is the link portion // iter refers to the first data node

Delete
before->next = after; // remove a node

delete pCur; pCur = NULL;

// delete memory

Insert
before->next = new Node(item, after); // insert a node

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Linked List Utility Functions


Allocate node
class Node { public: // define a constructor Node(const ItemType& item, Node* next) : item(item), next(next) {} ItemType item; Node* next; };

Node* CreateNode(const ItemType& item, Node* next) { return (new Node(item, next)); } // address if successful, NULL if not

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Linked List Utility Functions


Find Node
Node* FindNodeAt(const int pos) { // finds the node at location pos and returns its address

Node* iter = NULL;


if (pos >= 1 && pos <= Count) { iter = head; for (int skip = 1; skip < pos; skip++) { iter = iter->next; } } return (iter); }

6/21/2012 4:39 AM

Ch 4 - Linked Lists

Review : Linked List Utility Functions


Delete Nodes
void DeleteNodes() { // deletes all the nodes in the list

Node* del = head;


while (head != NULL) { head = head->next; delete del; del = head; } }

6/21/2012 4:39 AM

Ch 4 - Linked Lists

10

Review : Linked List Utility Functions


Copy Nodes
void CopyNodes(Node* copyHead) { // copies all the nodes in the list

tail = head = new Node(copyHead->item, NULL);


copyHead = copyHead->next;

while (copyHead != NULL) { tail = tail->next = new Node(copyHead->item, NULL); copyHead = copyHead->next; } }

6/21/2012 4:39 AM

Ch 4 - Linked Lists

11

C++ Exceptions
Error handling mechanism Catch and handle the exception (Use try...catch statement)
try { // statements that may cause an error } catch (ExceptionClass identifier) { // statements to handle the error } // one per handled exception

Throw an exception when error occurs


throw ExceptionClass(stringArgument);

// stringArgument is a more detailed error message

6/21/2012 4:39 AM

Ch 4 - Linked Lists

12

C++ Exceptions
/** @file ListIndexOutOfRangeException.h */ #include <stdexcept> #include <string> using namespace std; class ListIndexOutOfRangeException : public out_of_range { public: ListIndexOutOfRangeException(const string& message = "") : out_of_range(message.c_str()) {} }; /** @file ListException.h */ #include <stdexcept> #include <string> using namespace std; class ListException : public logic_error { public: ListException(const string& message = "") : logic_error(message.c_str()) {} };

6/21/2012 4:39 AM

Ch 4 - Linked Lists

13

C++ Exceptions
/** @file ListAexcept.h */ #include "ListException.h" #include "ListIndexOutOfRangeException.h" const int MAX_LIST = maximum-size-of-list; typedef desired-type-of-list-item ListItemType;

/** ADT list - Array-based implementation with exceptions */ class List { public: List(); /** @throw None. */ bool isEmpty() const; /** @throw None. */ int getLength() const; /** @throw ListIndexOutOfRangeException If index < 1 or index > getLength() + 1 * * @throw ListException If newItem cannot be placed in the list because the * array is full */ void insert(int index, const ListItemType& newItem) throw (ListIndexOutOfRangeException, ListException);

6/21/2012 4:39 AM

Ch 4 - Linked Lists

14

C++ Exceptions
/** @throw ListIndexOutOfRangeException If index < 1 or index > getLength(). */ void remove(int index) throw (ListIndexOutOfRangeException); /** @throw ListIndexOutOfRangeException If index < 1 or index > getLength(). */ void retrieve(int index, ListItemType& dataitem) const throw (ListIndexOutOfRangeException); private: /** array of list items */ ListItemType items[MAX_LIST]; /** number of items in list */ int size; int translate(int index) const; };

6/21/2012 4:39 AM

Ch 4 - Linked Lists

15

C++ Exceptions

void List::insert(int index, const ListItemType& newItem) throw (ListIndexOutOfRangeException) { if (size >= MAX_LIST) throw ListException("ListException: List full on insert"); if (index >= 1 && index <= size + 1) { } else { throw ListIndexOutOfRangeException( "ListIndexOutOfRangeException: Bad index on insert"); } }

6/21/2012 4:39 AM

Ch 4 - Linked Lists

16

Linked List : Example

// typedefs typedef int ItemType;

// Node definition struct Node { ItemType item; NodePtr next; // constructor to initialize struct Node(const ItemType& item, const Node* next) : item(item), next(next) {} };

6/21/2012 4:39 AM

Ch 4 - Linked Lists

17

ADT List : Pointer Based


class cListADT { private: struct Node; // forward declaration typedef Node* nodePtr; int size; nodePtr head; public: typedef int ItemType; // constructors cListADT(); cListADT(const cListADT& copyList); // destructor ~cListADT(); // member functions bool IsEmpty() const; int Length() const; bool Insert(int insertPos, ItemType insertValue); bool Delete(int deletePos); bool Retrieve(int retrievePos, ItemType& retrieveItem) const;

// default // copy

6/21/2012 4:39 AM

Ch 4 - Linked Lists

18

ADT List : Pointer Based


// overloaded functions cListADT operator =(const cListADT& rhs); private: // structure Node struct Node { Node(const ItemType& item, const node* next) : item(item), next(next) {} ITemType item; nodePtr next; }; // utility functions nodePtr NewNode(const ItemType& newValue, const nodePtr next); void AddNode(nodePtr before, nodePtr after); void DeleteNode(nodePtr before, nodePtr iter); nodePtr Find(int index) const; void DeleteList(); };

6/21/2012 4:39 AM

Ch 4 - Linked Lists

19

C++ STL
Support for predefined ADTs
Iterators, Algorithms, Containers

Containers
objects that hold other objects depend heavily on the class template construct

Iterators
way to cycle through the objects of a container use the * operator to access object are usually bidirectional (++, --)

Algorithms
act on the containers
6/21/2012 4:39 AM Ch 4 - Linked Lists 20

C++ STL
refer to p226 for more examples
list<int> myList; list<int>::iterator iter; // start at the beginning iter = myList.begin(); // insert five items into the list for (int j = 0; j < 5; j++) { // places j at the front of the list iter = myList.insert(iter, j); } // display the list for (iter = myList.begin(); iter != myList.end(); iter++) { cout << *iter << endl; }

6/21/2012 4:39 AM

Ch 4 - Linked Lists

21

Вам также может понравиться