Você está na página 1de 13

CS 1704 Intro to Data Structures & Software Eng.

Linked List Classes 7. LL Class 1 Linked List Example 7. LL Class 2

Slides This chapter presents a sample implementation of a linked list, encapsulated in a C++
class.
1. Table of Contents
2. Linked List Example The primary goals of this implementation are:
• to provide a proper separation of functionality.
3. Node Class
• to design the list to serve as a container; i.e., the list should be able to store
4. Node Class Constructors data elements of any type.
5. Node Class Mutators
6. Node Class Reporters First, a LinkNode class is used to encapsulate the low-level pointer operations.
7. Linked List Class
8. LinkList Constructor Second, a LinkList class is used to encapsulate a list of LinkNode objects.
9. LinkList Destructor
10. LinkList Reporters Third, an Item class is used to encapsulate the data and separate it from the pointers
11. LinkList PrefixMutator that define the list structure.
12. LinkList Insert Mutator
13. LinkList Position Mutators The basic view is that each list node provides a data “socket” that is capable of
accepting any type of data element:
14. LinkList Delete Curr Mutator
15. LinkList Delete Value Mutator
16. LinkList Set Curr Mutators Data
17. LinkList Reporter Element
Data Element Class

Next
18.
19. Data Element Class Equality Operator “Data Socket”
20. LinkList Search
21. Alternate Implementation
22. Merge Lists (preservation)
23. Ordered Insertion
Warning: the LinkList class given in this chapter is intended for
24. Merge Lists (no preservation) in situ instructional purposes. The given implementation contains a
25. Merge Lists in situ (cont) number of known flaws, and perhaps some unknown flaws as
well. Caveat emptor.

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Node Class 7. LL Class 3 Node Class Constructors 7. LL Class 4

LinkNode class is used to encapsulate pointer operations: LinkNode constructor implementations:


// LinkNode.h // LinkNode.cpp
// //
// The LinkNode class provides a simple #include "LinkNode.h" // for class declaration
// implementation
// for nodes of a singly-linked list structure. //////////////////////////////////////////////////
// // Default constructor for LinkNode objects.
// The user must provide a declaration and //
// implementation of a class named Item in // Parameters: none
// order for the given implementation of LinkNode // Pre: none
// to be valid. // Post: new LinkNode has been created with
// // default Data field and NULL
#ifndef LINKNODE // pointer
#define LINKNODE //
#include "Item.h" // for Item type declaration LinkNode::LinkNode() { Uses
Usesdefault
default
//explicit initialization of construction
class LinkNode { //Data member unnecessary constructionfor
for
Item objects.
Item objects.
private: Next = NULL;
Item Data; // data "capsule" }
LinkNode* Next; // pointer to next node
//////////////////////////////////////////////////
public: // Constructor for LinkNode objects with assigned
LinkNode(); const // Data field.
LinkNode(const Item& newData); constfor
forprotection
protection //
void setData(const Item& newData); // Parameters:
void setNext(LinkNode* const newNext); // newData Data element to be stored in node
Item getData() const; // Pre: none
LinkNode* getNext() const; // Post: new LinkNode has been created with
}; Why does LinkNode not // given Data field and NULL
contain a destructor? // pointer
#endif //
LinkNode::LinkNode(const Item& newData) {
Data = newData;
// to define a LinkNode pointer type
Next = NULL; Uses
class LinkNode; // Forward declaration } Usesdefault
default(or
(oroverloaded)
overloaded)
typedef LinkNode* NodePtr; assignment
assignmentfor
forItem
Itemobjects.
objects.

The LinkNode class neither knows nor cares what an Item variable
is — a LinkNode is a container. We are assuming that Item is a class. (Do you see where?)

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Node Class Mutators 7. LL Class 5 Node Class Reporters 7. LL Class 6

LinkNode mutator implementations : LinkNode reporter implementations :


////////////////////////////////////////////////// //////////////////////////////////////////////////
// Sets new value for Data element of object. // Returns value of Data element of object.
// //
// Parameters: // Parameters: none
// newData Data element to be stored in node // Pre: object has been initialized
// Pre: none // Post: Data field of object has been
// Post: Data field of object has been // returned
// modified to hold newData //
// Item LinkNode::getData() const { Uses
Usesconst
consttoto
void LinkNode::setData(const Item& newData) { guarantee
guaranteenono
return Data; modification
Data = newData; } modificationoccurs.
occurs.
}
//////////////////////////////////////////////////
////////////////////////////////////////////////// // Returns value of Next pointer of object.
// Sets new value for Next pointer of object. //
// // Parameters: none
// Parameters: // Pre: object has been initialized
// newNext new value for pointer field // Post: Next field of object has been
// Pre: none // returned
// Post: Next field of object has been //
// modified to hold newNext LinkNode* LinkNode::getNext() const {
//
void LinkNode::setNext(LinkNode* const newNext) { return Next;
}
Next = newNext;
}

Why is the parameter to


setNext not passed as:
const LinkNode* const newNext

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Linked List Class 7. LL Class 7 LinkList Constructor 7. LL Class 8

LinkList class is used to encapsulate all high-level list operations: Code


// LinkList.h // LinkList.cpp
// The LinkList class provides an implementation for a //
// singly-linked list consisting of ListNode objects. #include "LinkList.h"
//
// User must provide a declaration and implementation
// of a class named Item with a default constructor and //////////////////////////////////////////////////
// an overloaded == operator in order for the given // Default constructor for LinkList objects.
// implementation of LinkNode to be valid. //
// Parameters: none
#ifndef LINKLIST_H // Pre: none
#define LINKLIST_H // Post: new empty LinkList has been created
//
#include <cassert> LinkList::LinkList() {
Head = Tail = Curr = NULL;
#include "LinkNode.h" // for node declaration }
//#include "Item.h" // must be included by user

class LinkList {
private: The object definition:
LinkNode* Head; // points to head node in list
LinkNode* Tail; // points to tail node in list LinkList TheList;
LinkNode* Curr; // points to "current" node
public:
LinkList(); //constructor One
Oneline
lineFns
Fnscould
couldbe
be
Results in the following state:
~LinkList();//destructor “inline” for efficiency.
bool isEmpty() const; “inline” for efficiency. TheList
bool inList() const;
bool PrefixNode(const Item& newData); Head Curr Tail
bool Insert(const Item& newData);
bool Advance();
void gotoHead();
• • •
void gotoTail(); consts
constsfor
forprotection
protection
bool DeleteCurrentNode();
bool DeleteValue(const Item& Target);
Item getCurrentData() const;
void setCurrentData(const Item& newData);
// missing: copy constructor, assignment overload FNs
};
#endif See Copying Objects notes for missing functions.

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

LinkList Destructor 7. LL Class 9 LinkList Reporters 7. LL Class 10

Code Code
////////////////////////////////////////////////// //////////////////////////////////////////////////
// Default destructor for LinkList objects. // Indicates whether LinkList is empty.
// //
// Parameters: none // Parameters: none
// Pre: LinkList object has been constructed // Pre: LinkList object has been constructed
// Post: LinkList object has been destructed; // Post: returns true if object contains an
// all dynamically-allocated nodes // empty list, and false otherwise
// have been deallocated. //
// bool LinkList::isEmpty() const {
LinkList::~LinkList() {
return (Head == NULL);
LinkNode* toKill = Head; }

while ( toKill != NULL) { //////////////////////////////////////////////////


Head = Head->getNext(); // Indicates whether the current pointer for the
delete toKill; // LinkList object has a target.
toKill = Head; //
} // Parameters: none
Head = Tail = Curr = NULL; // Pre: LinkList object has been constructed
} // Post: returns true if current pointer has
// a target, and false otherwise
Compiler generates calls to the destructor automatically whenever //
bool LinkList::inList() const {
a LinkList object goes out of scope (i.e. its lifetime ends: at the end
of the function/block in which the objects are defined, when a return (Curr != NULL);
}
dynamically allocated object is destroyed with delete(), when an
object containing a member object is destroyed).
LinkList uses a pointer (Curr) to keep a sense of the current
A class destructor’s names is always the tilde followed by the position in the list as operations are performed.
name of the class. It has no parameters or return type and cannot This isn’t absolutely necessary (especially if the list is to be kept
be overloaded. sorted in some order), but it is useful for general lists.

LinkList needs a destructor in order to properly return the


dynamically-allocated nodes to the system heap.

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

LinkList PrefixMutator 7. LL Class 11 LinkList Insert Mutator 7. LL Class 12

Code: inserting at the head of the list Code: inserting after the current position
////////////////////////////////////////////////// //////////////////////////////////////////////////
// Inserts a new LinkNode at the front of the // Inserts a new LinkNode immediately after the
// list. // current position in the list.
// //
// Parameters: // Parameters:
// newData Data element to be inserted // newData Data element to be inserted
// Pre: LinkList object has been constructed // Pre: LinkList object has been constructed
// Post: LinkNode containing newData has been // Post: LinkNode containing newData has been
// constructed and inserted at the // constructed and inserted after
// beginning of the list, if // the current position, if possible.
// possible. //
// // Returns: true if operation succeeds
// Returns: true if operation succeeds // false otherwise
// false otherwise //
// bool LinkList::Insert(const Item& newData) {
bool LinkList::PrefixNode(const Item& newData) {
if (Curr == NULL) return false;
LinkNode* newNode = new(nothrow) LinkNode(newData);
LinkNode* newNode = new(nothrow) LinkNode(newData);
if (newNode == NULL) return false;
if (newNode == NULL) return false;
if ( isEmpty() ) { Pointer
Pointerdereference.
dereference.
newNode->setNext(NULL); This
Thisisisaavery
verygood
goodplace
place if ( isEmpty() ) Why should this
Head = Tail = Curr = newNode; to return false;
return true; toblow
blowup upatatruntime
runtimeifif case never occur?
you
youdon’t
don’tverify
verifynewNode
newNode
} isisnot newNode->setNext(Curr->getNext());
notNULL
NULLprior
priorto
tothis
this Curr->setNext(newNode);
newNode->setNext(Head); statement.
statement. if (Curr == Tail)
Head = newNode; Tail = newNode;
IsIsthis
thisstatement
statement
return true; necessary? return true;
} necessary?(Included
(Includedas
as }
aaprecaution?)
precaution?) Note
Notetest
testfor
forvalid
valid
current
currentposition.
position.
Uses
UsesLinkNode
LinkNodemember
memberfunctions
functionsto
tomodify
modify
node
nodepointers
pointers——thisthisgives
givesaaseparation
separationbetween
between
the
the“high”
“high”level
levellist
listfunctions
functionsthe
theuser
usersees
seesand
and
the
the“massaging”
“massaging”of ofthe
thepointers.
pointers.

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

LinkList Position Mutators 7. LL Class 13 LinkList Delete Curr Mutator 7. LL Class 14

Code: changing the current position Code: deleting the current node
/////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
// Resets the current position to the head of the list. // Deletes the node at the current position, if possible.
// //
void LinkList::gotoHead() { // Returns: true if operation succeeds false otherwise
//
Curr = Head; bool LinkList::DeleteCurrentNode() {
}
LinkNode* delThis;
/////////////////////////////////////////////////////// Test
Testfor
forvalid
validcurrent
current
// Resets the current position to the tail of the list. if (Curr == NULL) return false; position.
position.
//
void LinkList::gotoTail() { if (Curr == Head) { //delete Head node
delThis = Curr; Handle
Curr = Tail; Head = Head->getNext(); Handledeletion
deletionof
of
} Curr = Head; head
headnode.
node.
if (Tail == delThis) Tail = Curr;
////////////////////////////////////////////////// delThis->setNext(NULL);
// Advances the current position to the next node delete delThis;
// in the list, if there is one; leaves the return true;
// current position unchanged otherwise. }
//
// Parameters: none //locate Curr's previous node
// Pre: LinkList object has been constructed LinkNode* prevNode = Head; Find
// Post: Current position advanced to the while (prevNode != NULL && Findprevious
previousnode.
node.
// next node, if possible. prevNode->getNext() != Curr)
// prevNode = prevNode->getNext();
// Returns: true if operation succeeds
// false otherwise //check for valid Curr pointer IfIfnot
notfound,
found,error.
error.
// if (prevNode == NULL) return false;
bool LinkList::Advance() {
Note //previous found bypass and delete Curr
if (Curr != NULL) { Notetest
testfor
forvalid
valid delThis = Curr; Handle
Curr = Curr->getNext(); current
currentposition.
position. Handledeletion
prevNode->setNext(Curr->getNext()); node deletionof
of
return true; Curr->setNext(NULL); nodeininmiddle
middleor
oratat
} Curr = prevNode->getNext(); tail of list.
tail of list.
else if (Tail == delThis) Tail = prevNode;
return false; delete delThis;
} return true;
}

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

LinkList Delete Value Mutator 7. LL Class 15 LinkList Set Curr Mutators 7. LL Class 16

Code: deleting a list value Code: changing the Data in the current node
////////////////////////////////////////////////// //////////////////////////////////////////////////
// Deletes the (first) node in the list that // Replaces the Data element of the current node,
// contains the specified Data element. // if possible; assert() failure will kill program
// // if not, so test with inList() before calling.
// Parameters: //
// Target Data value to be deleted // Parameters:
// Pre: LinkList object has been constructed // newData Data element used for updating
// Equality oper. overloaded for Item // Pre: LinkList object has been constructed
// Post: First node in the list that contains // Post: Data element of current node has
// the specified data value has // been updated, if possible.
// been deleted. //
// void LinkList:: setCurrentData(const Item& newData) {
// Returns: true if operation succeeds
// false otherwise assert (Curr != NULL);
//
bool LinkList::DeleteValue(const Item& Target) { Curr->setData(newData); IfIfno
nocurrent
current
} position,
position,die.
die.
LinkNode* myCurr = Head;
LinkNode* myTrailer = NULL; Look
Lookfor
formatching
matchingnode.
node.
while ( (myCurr != NULL) &&
!(myCurr->getData() == Target) ) { This implementation places a burden on the user of the class. If
myTrailer = myCurr;
myCurr = myCurr->getNext(); the current position is undefined (e.g., if the list is empty), then the
} IfIfnot
notfound,
found,error.
error.
call to assert() will cause the program to terminate rather
if (myCurr == NULL) return false;
gracelessly. A better design would alert the user/client:
if (myTrailer == NULL) Handle
Handlecase
casetarget
targetisis
Head = Head->getNext(); the
thehead
headnode.
node.
else bool LinkList:: setCurrentData(const ItemType& newData)
myTrailer->setNext(myCurr->getNext()); {

if (Curr == myCurr) Curr = myTrailer; if (!Curr) return false;


if (Tail == myCurr) Tail = myTrailer;
myCurr->setNext(NULL); Curr->setData(newData);
delete myCurr; return true;
return true; Handle
Handledeletion
deletionof
of }
} node
nodeininmiddle
middleor
oratat
tail
tailof
oflist.
list.

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

LinkList Reporter 7. LL Class 17 Data Element Class 7. LL Class 18

Code: returning the Data in the current node The user must typedef Item to match the data class that he/she
really wishes to use. Recall the Inventory Class:
//////////////////////////////////////////////////
// Returns the Data element of the current node,
// if possible; assert() failure will kill program // *********** INVENTORY CLASS DECLARATION ************
// if not, so test with inList() before calling.
// class InvItem {
// Parameters: none private:
// Pre: LinkList object has been constructed string SKU; //StocK Unit #: KEY FIELD
// Post: Data element of current node has string Description; //Item Details
// been returned, if possible. int Retail; //Selling Price
// int Cost; //Store Purchase Price
Item LinkList::getCurrentData() const {
int Floor; //Number of Items on display
IfIfno int Warehouse; //Number of Items in stock
assert (Curr != NULL); nocurrent
current
position,
position,die.
die.
return (Curr->getData()); public:
} InvItem(); //default constructor
InvItem(const string& iSKU, //parameter constructor
const string& iDescription,
This possible premature termination due to an undefined current int iRetail,
position could be eliminated by having the function return a int iCost,
int iFloor,
pointer to a copy of the data element, or by having the function use int iWarehouse);
a reference parameter to communicate a copy of the data value to
//Reporter Member Functions
the caller, and also return true/false to indicate success. // . . . Unchanged from previous declaration
//Mutator Member Functions
Better design: maintain an internal error state in the class. (E.g., // . . . Unchanged from previous declaration
similar to the stream status in <iostream>). //Operator Overloads
bool operator==(const InvItem& anItem);
Note: a pointer to an object in a list (i.e. Item*) or a reference to }; // class InvItem
an object in a list (i.e. Item&) should NOT be returned by a
member function. Why? typedef InvItem Item; Required type name
equivalency definition

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Data Class Equality Operator 7. LL Class 19 LinkList Search 7. LL Class 20

Inventory class equality operator: Sequential search function for LinkList:

//-------------- Operator Overload Functions --------- //////////////////////////////////////////////////////


// Search function for LinkList Item objects.
/////////////////////////////////////////////////////// //
// Operator == Fn for InvItem Class // Parameters:
// // List a LinkList object
// Parameters: an Item to compare // Item a Item object
// Pre: members have been initialized // Pre: LinkList object has been constructed
// Post: T/F comparison of SKUs returned // Equality oper. overloaded for Item
// // Post: returns true if anItem is found in List
bool InvItem::operator==(const InvItem& anItem){ // and false otherwise
//
return (SKU == anItem.getSKU()); bool Search(LinkList& List, const Item& anItem) {
}
if (List.isEmpty())
return false;
else {
List.gotoHead();
This simple operator overload function is required for the correct while( (List.inList()) &&
!((List.getCurrentData() == anItem)) )
use of the LinkList class. The DeleteValue() function List.Advance();
assumes that two Item objects can be compared for equality, (but return (List.inList());
not inequality). }
} // Search

By only testing the SKU members for equality the code is Note: this function is “external” to the LinkList class. The inclusion of
reflecting a design decision that the SKU numbers of all Inventory the function as a LinkList class member function is left as an exercise.
items must be unique.
//OK? Why is the second condition in the while boolean expression not stated:
return (SKU == anItem.SKU); (anItem != (List.getCurrentData())
Even more subtle, why can it not also be stated:
!(anItem == (List.getCurrentData()))

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Alternate Implementation 7. LL Class 21 Merge Lists (preservation) 7. LL Class 22

/* Given 2 ascending ordered single linked-lists,


Alternate PrefixNode() Implementation: return a new ordered list which contains all of
the elements of both lists, (the original lists
////////////////////////////////////////////////// must NOT be destroyed by the merging). */
// Inserts a new LinkNode at the front of the
// list. LinkList MergeLists(LinkList L1, LinkList L2){
// Item TmpData;
// Parameters: LinkList merge;
// newData Data element to be inserted
// Pre: LinkList object has been constructed L1.gotoHead();
// Post: LinkNode containing newData has been while (L1.inList()) {
// constructed and inserted at the AddList(merge,
// beginning of the list, if
TmpData = L1.getCurrentData(); AddList(merge,L1)
L1); ;
insertion(merge, TmpData);
// possible. L1.Advance();
// }
// Returns: true if operation succeeds
// false otherwise AddList(merge,
//
L2.gotoHead(); AddList(merge,L2)
L2); ;
while (L2.inList()) {
bool LinkList::PrefixNode(const Item& newData) { TmpData = L2.getCurrentData();
insertion(merge, TmpData);
LinkNode newNode(newData); L2.Advance();
} //No
//Nopreservation
preservation
if ( isEmpty() ) { L1.~LinkList();
L1.~LinkList();
newNode.setNext(NULL); return merge; L2.~LinkList();
Head = Tail = Curr = &newNode; L2.~LinkList();
}
return true;
}
void AddList(LinkList& target, LinkList source)
newNode.setNext(Head); {
Head = &newNode; Item TmpData;

return true; source.gotoHead();


} while (source.inList()) {
TmpData = source.getCurrentData();
insertion(target, TmpData);
source.Advance();
Is the above implementation superior or inferior to the original }
}
implementation of PrefixNode(), see slide 7.11? insertion(performs
insertion(performs
an
anordered
orderedinsert)
insert)
WARNING:
WARNING:untested
untestedcode!
code!

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Merge Lists (no preservation)


Ordered Insertion 7. LL Class 23 7. LL Class 24
in situ
/* Given 2 ascending ordered single linked-lists, merge
Non-class, (non-member), function to perform an ordered all of the elements of both lists together returned
LinkList insertion. through the first list, (the second list is destroyed by
the merging). */

// Insert the Item in the ascending ordered LinkList void LinkList::Mergelists(LinkList& L2) {

bool insertion(LinkList& list, const Item & newData){ LinkNode* MergeHead; Assumes
LinkNode* trail1; Assumeselements
elements
list.gotoHead(); LinkNode* trail2; within
withinlist
listare
areunique.
unique.
Item i1, i2;
while ( (list.inList()) &&
(list.getCurrentData() < newData ) ) if (Head == NULL) { //this empty return L2 List
list.Advance(); Head = L2.Head; L2.Head = NULL;
Curr = L2.Curr; L2.Curr = NULL;
if (list.isEmpty()) Tail = L2.Tail; L2.Tail = NULL;
return(list.PrefixNode(newData)); return;
else if (!list.inList()) { //newData > tail }//if
list.gotoTail(); //append to tail if (L2.Head == NULL) //return this List
return(list.Insert(newData)); return;
}
else { //insert before Current list element // set merge list head to smaller first item
Item tmpData = list.getCurrentData(); MergeHead = (Head->getData() < L2.Head->getData())
list.setCurrentData(newData); ? Head : L2.Head;
return(list.Insert(tmpData));
} while ( (Head != NULL) && (L2.Head != NULL) ) {
} i1 = Head->getData();
Sets
Setscurrent
currentnode
nodetoto i2 = L2.Head->getData();
contain
containnewData
newDataitem
item
and
and inserts old nodedata
inserts old node data if ( i1 == i2 ){//egual current merge items
item trail2 = L2.Head->getNext();//advance L2.Head
itemafter
aftercurrent
currentnode.
node. L2.Head->setNext(Head); //due to initial/curr
L2.Head = trail2; //equal elements
}//if
while
whileconditions
conditionsrely
relyupon
upon
Boolean
Booleanshort-circuiting.
short-circuiting.

Problem:
Problem:ififList2
List2contains
contains
multiple
multipleitems
itemsequal
equalto
to
WARNING:
WARNING:untested
untestedcode!
code! WARNING:
WARNING:untested
untestedcode!
code! head of list1?
head of list1?

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes


CS 1704 Intro to Data Structures & Software Eng.

Merge Lists in situ (cont) 7. LL Class 25

else
if ( i1 < i2 ) { //advance this list
while ( (Head != NULL) && //until end of list
(Head->getData() < i2) ) { //or smaller
trail1 = Head; // item is found
Head = Head->getNext();
} //while
trail1->setNext(L2.Head);
} //if
else { //i2 < i1 //advance L2 list
while ( (L2.Head != NULL) &&//until end list
(L2.Head->getData() < i1) ) { //or
trail2 = L2.Head; //smaller item is
L2.Head = L2.Head->getNext(); //found
} //while
trail2->setNext(Head);
} //else

} //while

if ( Head == NULL )//L2 is longer list


Tail = L2.Tail; //update Tail

L2.Head = L2.Tail = L2.Curr = NULL;


Head = MergeHead;
}
Duplicated
Duplicatedcode
code
should
shouldbe
beeliminated.
eliminated.

WARNING:
WARNING:untested
untestedcode!
code!

Computer Science Dept Va Tech Aug., 2001 Intro Data Structures & SE ©1995-2001 Barnette ND, McQuain WD

Lined List Classes

Você também pode gostar