ch04 linked lists

Upload: ashwn17

Post on 05-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Ch04 Linked Lists

    1/21

    LINKED LISTS

    6/21/2012 4:39 AM Ch 4 - Linked Lists 1

  • 7/31/2019 Ch04 Linked Lists

    2/21

    Value v. Reference

    6/21/2012 4:39 AM Ch 4 - Linked Lists 2

    Stack...

    100 x: 10

    96 xptr: 0x100

    92 yptr: 0x12

    ...

    Heap

    ...

    12 10

    8

    4

    ...

    int x = 10;

    int *xptr = &x;

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

    delete yptr;

  • 7/31/2019 Ch04 Linked Lists

    3/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 3

    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 refers to x (static allocation)

    *p = 20; // change x to 20

    int *p1 = new int; // p1 refers to an allocated int (dynamic allocation)

    *p1 = 100; // assign 100 to allocated int

    delete p1; // deallocate memory held by int

    p1 = NULL; // p1 refers to nothing

  • 7/31/2019 Ch04 Linked Lists

    4/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 4

    Review : Pointers

    Dynamic memory is allocated on the heap using new

    Must be deallocated, using delete

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

    int *p = new int [100]; // p refers to an array of ints

    p[0] = 1; // first element is assigned the value 1

    delete [] p; // delete the allocated array

    struct Box { // struct definition

    int len, width;

    };

    Box *b = new Box; // b refers to an allocated struct

    b->len = 10; // len member is set to 10

    delete b; // memory deallocated

    b = NULL;

  • 7/31/2019 Ch04 Linked Lists

    5/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 5

    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

    }

    }

  • 7/31/2019 Ch04 Linked Lists

    6/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 6

    Review : Linked List

    Display

    Delete

    Insert

    Node* iter = head; // iter refers to the first node

    while (iter != NULL) {

    cout item next; // next is the link portion

    }

    head = head->next; // remove first node

    before->next = after; // remove other node

    delete del; // delete memory

    del = NULL;

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

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

  • 7/31/2019 Ch04 Linked Lists

    7/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 7

    Review : Linked List Head Node

    Display

    Delete

    Insert

    Node* iter = head->next; // iter refers to the first data node

    while (iter != NULL) {

    cout item next; // next is the link portion

    }

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

    delete pCur; // delete memory

    pCur = NULL;

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

  • 7/31/2019 Ch04 Linked Lists

    8/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 8

    Review : Linked List Utility Functions

    Allocate node

    Node* CreateNode(const ItemType& item, Node* next) {

    return (new Node(item, next)); // address if successful, NULL if not}

    class Node {public:

    // define a constructor

    Node(const ItemType& item, Node* next)

    : item(item), next(next)

    {}

    ItemType item;

    Node* next;

    };

  • 7/31/2019 Ch04 Linked Lists

    9/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 9

    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 next;

    }

    }

    return (iter);

    }

  • 7/31/2019 Ch04 Linked Lists

    10/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 10

    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;

    }

    }

  • 7/31/2019 Ch04 Linked Lists

    11/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 11

    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;

    }

    }

  • 7/31/2019 Ch04 Linked Lists

    12/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 12

    C++ Exceptions

    Error handling mechanism

    Catch and handle the exception (Use try...catchstatement)

    Throw an exception when error occurs

    try {

    // statements that may cause an error

    }

    catch (ExceptionClass identifier) { // one per handled exception

    // statements to handle the error

    }

    throw ExceptionClass(stringArgument);

    // stringArgument is a more detailed error message

  • 7/31/2019 Ch04 Linked Lists

    13/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 13

    C++ Exceptions

    /** @file ListIndexOutOfRangeException.h */

    #include #include

    using namespace std;

    class ListIndexOutOfRangeException : public out_of_range

    {

    public:

    ListIndexOutOfRangeException(const string& message = "")

    : out_of_range(message.c_str())

    {}

    };

    /** @file ListException.h */

    #include

    #include

    using namespace std;

    class ListException : public logic_error

    {

    public:

    ListException(const string& message = "")

    : logic_error(message.c_str())

    {}

    };

  • 7/31/2019 Ch04 Linked Lists

    14/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 14

    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);

  • 7/31/2019 Ch04 Linked Lists

    15/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 15

    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;

    };

  • 7/31/2019 Ch04 Linked Lists

    16/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 16

    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

  • 7/31/2019 Ch04 Linked Lists

    17/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 17

    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)

    {}

    };

  • 7/31/2019 Ch04 Linked Lists

    18/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 18

    ADT List : Pointer Based

    class cListADT {

    private:struct Node;

    // forward declaration

    typedef Node* nodePtr;

    int size;

    nodePtr head;

    public:

    typedef int ItemType;

    // constructors

    cListADT(); // default

    cListADT(const cListADT& copyList); // copy

    // destructor

    ~cListADT();

    // member functionsbool IsEmpty() const;

    int Length() const;

    bool Insert(int insertPos, ItemType insertValue);

    bool Delete(int deletePos);

    bool Retrieve(int retrievePos, ItemType& retrieveItem) const;

  • 7/31/2019 Ch04 Linked Lists

    19/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 19

    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();};

  • 7/31/2019 Ch04 Linked Lists

    20/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 20

    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

  • 7/31/2019 Ch04 Linked Lists

    21/21

    6/21/2012 4:39 AM Ch 4 - Linked Lists 21

    C++ STL

    refer to p226 for more examples

    list myList;

    list::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