Sie sind auf Seite 1von 10

LAB SESSION 1 BASIC OPERATIONS ON LINKED LIST 1.

OBJECTIVE The objectives of Lab 1 are (1) to introduce on how to represent a linked list as an OO class; (2) to implement some basic operations on linked list and (3) to use an preimplemented class of linked list; 2. EXAMPLE This section gives an example on how to represent a linked list as a class, as well as implement some basic operations of the linked list. The way to use an implemented linked list is also introduced. Listing 1 gives an example of a class representing a node in a linked list. As stated in the lectures, a node in a linked list consists of two parts: data and the link to the next node.
class Node { public: int data; Node* next; }

Listing 1 Listing 2 illustrates a simple way to create a linked list using the Node class. The list consisted of 3 elements: {2,3,5}. We use the pointer pHead to keep track of the first element of the list, meanwhile count reflecting the number of list elements. We also use a temporary pointer pTemp for our work. To check that our code runs correctly, we use a loop to print out all of elements data.
void main() { //declaration Node * pHead = NULL; int count = 0; Node* pTemp = NULL; //make the list

pTemp = new Node; count++; pTemp->data = 5; pTemp->next = NULL; // pHead = pTemp; // the list now is {5} pTemp = new Node; count++; pTemp->data = 3; pTemp->next = pHead; pHead = pTemp; // the list now is {3,5} pTemp = new Node; count++; pTemp->data = 2; pTemp->next = pHead; pHead = pTemp; // the list now is {2,3,5} //print them out while (pTemp!=NULL) { cout << pTemp->data; pTemp = pTemp->next; } }

Listing 2 In that way, our program looks ill-organized. In Listing 3, we then improve it by combining pHead, count into a class named List. Then the operation of inserting a new element into the list will be implemented as the method addFirst. We also implement method display to print out the list elements. Note that we use constructor to initialize the head of the list as NULL, and destructor to free the memory allocated.
class List { private: int count; Node* pHead; public: List() {pHead=NULL;} void addFirst(int newdata) { Node* pTemp = new Node; pTemp->data = newdata;

pTemp->next = pHead; pHead = pTemp; count++; } void display() { Node* pTemp = pHead; while (pTemp!=NULL) { cout << pTemp->data; pTemp = pTemp->next; } } ~List() { Node* pTemp = pHead; while (pTemp!=NULL) { pTemp = pTemp->next; delete pHead; pHead = pTemp; } } }

Listing 3 Having the List class implemented, the main function can be rewritten far simpler as depicted in Listing 4.
void main() { List aList; aList.addFirst(5); aList.addFirst(3); aList.addFirst(2); aList.display();

} Listing 4 The implementation of a class for linked list as above-described in this section is just an example. There are many other variations of implementations for linked list as discussed

in the Appendix section. Students can choose what they feel appropriate when working with exercises and assignments.

4. EXERCISES 4.1. Rewrite the main function in Listing 4 to build and display a linked list as follows {12, 5, 79, 82, 21, 43, 31, 35, 57}. 4.2. Consider the following function
List* buildLinkedList() { List *pList = new List; int valid=1; char choice; int num; while (valid) { cout << Do you want to enter a number? (Y/N):; cin >> choice; if ((choice == Y) || (choice == y)) { cin >> num; pList->addFirst(num); } else valid = 0; } return pList; }

Rewrite the main function in Exercise 4.1 to do the following tasks: use the buildLinkedList function to create a list based on input from user. display the list free the memory allocated to the list

4.3. Write for the class List in Listing 3 an additional method int addFirstIfPrime(int
n) which adds n to the list if n is a prime integer. In that case the returned result is 1,

otherwise 0.

4.4. Write for the class List in Listing 3 an additional method int addLast(int n) which adds n to the last position of the list. 4.5. Implement the following method int findMax(List* pList) It will return the maximum element data of the given list. Assume that pList is always non-empty. For example, when called with the list as built in Exercise 4.1, the returned result is 82. APPENDIX This section introduces various techniques on how to implement linked list in C/C++. For more information, please refer to the lecture note in file Chapter2_LinkedList_Implementation.pdf on Sakai. a Pointer in C++ Node *ptr; Khai bo mt con tr ptr c kiu Node *, ngha l con tr cha a ch ca mt vng nh kiu Node. Cp pht vng nh v cho con tr ptr ch n.

ptr = new Node();

printf(Data in node: %d, ptr->data); In gi tr kiu int ca thnh phn data ca vng nh (kiu Node) do con tr ptr ch n. (C th gi tt l thnh phn data ca con tr ptr.) delete ptr; ptr = NULL; b. Nodes in C++ node data <dataType> link <pointer> end node Hy vng nh ti con tr ptr (con tr ptr ang ch n) Gn con tr ptr n NULL

//C struct struct Node { int data; Node * link; }; //C++ template struct template<class ItemType> struct Node { ItemType data; Node<ItemType> * link;

}; //C++ template class template<class ItemType> class Node { ItemType data; Node<ItemType> * link; public: Node() { //default constructor: is called in creating, for example by calling new Node() this->link = NULL;} Node(ItemType data) { //constructor: is called in creating with parameters, for example by calling new Node(data) this->data = data; this->link = NULL; } }; ... Node<int> *p = new Node<int>(); //default constructor Node<double> *q = new Node<double>(3.2); //constructor Node<float> z(0.5); //constructor c. Linked List in C++ list count <integer> head <pointer> end list

//C struct struct List { int count; Node * head; }; //C++ template struct template<class ItemType> struct List { int count; Node<ItemType> * head; }; //C++ template class template<class ItemType> class List { int count; Node<ItemType> * head; public: List(); //constructor: use to initialize internal data

list head <pointer> tail <pointer> end list

No structure list <pointer>

~List(); //destructor: use to release internal data }; //C++ template class template<class ItemType> class List { Node<ItemType> * head; Node<ItemType> * tail; public: List(); //constructor: use to initialize internal data ~List(); //destructor: use to release internal data }; //Only a pointer for the head of the list Node * list; Node<int> * list;

d. Linked List Operations in C++ algorithm createList (ref list //C struct <metadata>) void createList(List &list) { Initializes metadata for a linked list list.head = NULL; Pre list is a metadata structure passed by list.count = 0; reference } Post metadata initialized //C++ template class, default constructor template <class ItemType> 1. list.head = null LinkedList<ItemType>::LinkedList(){ 2. list.count = 0 this->head = NULL; 3. return this->count = 0; end createList } algorithm destroyList (ref list //C struct <metadata>) void destroyList(List &list) { Node *tmp; Deletes all data in list. while (list.head != NULL){ Pre list is metadata structure to a valid temp = list.head; list list.head = list.head->next; Post all data deleted delete temp; 1. loop (list.head not null) } 1. tmp = list.head list.count = 0; 2. list.head = list.head-> link }

3. recycle (tmp) No data left in list. Reset metadata 2. list.count = 0 3. return end destroyList

//C++ template class, Clear method template <class ItemType> void LinkedList<ItemType>::Clear(){ Node<ItemType> *temp; while (this->head != NULL){ temp = this->head; this->head = this->head->next; delete temp; } this->count = 0; } //the destructor method calls Clear template <class ItemType> LinkedList<ItemType>::~LinkedList(){ this->Clear(); }

e. Using Linked List in C/C++ algorithm ABC () 1. create a linked list myList 2. insert 15 at the beginning of myList 3. insert 5 at the beginning of myList 4. insert 18 at position 2 of myList 5. insert 25 at the end of myList 6. remove item at position 2 of myList 7. print myList 8. delete myList end ABC

//C struct void ABC() { List myList; insertFirst(myList, 15); insertFirst(myList, 5); insertItem(myList, 18, 2); insertLast(myList, 25); deleteItem(myList, 2); printList(); destroyList(myList); }

algorithm buildLinkedList This program read from the keyboard a list of integers and builds a linked list contains those integers in the reversed order. It also asks the user to enter a number every time. It will print the list. Pre nothing

//C++ template class, dynamic list declaration void ABC() { LinkedList<int>* myList = new LinkedList<int>(); myList->InsertFirst(15); myList->InsertFirst(5); myList->InsertItem(18, 2); myList->InsertLast(25); myList->DeleteItem(2); myList->Print2Console(); delete myList; //the delete statement release the memory holding by the pointer myList. In this case, the destructor is called automatically, and in turn it calls the Clear() method to destroy the list. } // C++ template class, static list declaration void ABC() { LinkedList<int> myList; myList.InsertFirst(15); myList.InsertFirst(5); myList.InsertItem(18, 2); myList.InsertLast(25); myList.DeleteItem(2); myList.Print2Console(); myList.Clear(); //the list can be destroyed explicitly using this way. Otherwise, the content of the list is remained until the end of the function (at that time, the list is destroyed when the destructor is called implicitly.) } LinkedList<int> *buildLinkedList () { LinkedList<int>* pList = new LinkedList<int>(); int valid=1; char choice; int num; while (valid) { cout << Do you want to enter a

number? (Y/N): << flush; cin >> choice; if ((choice == Y) || (choice == y)) { 1. createList(pList) cin >> num; 2. valid = true pList->insertFirst(num); 3. loop (valid true) } else 1. print (Do you want to enter a number?(Y/N):) valid = 0; 2. read (choice) } 3. if (choice equal Y) pList->printList(); 1. read (number) return pList; 2. insertFirst (pList,number) }
Post List has been built returns a List of Integer 4. else 1. valid = false 5. endif 4. end loop 5. printList(pList) 6. return (pList) end buildLinkedListOfInteger

Das könnte Ihnen auch gefallen