CS 150 Introduction to C++ Programming - Spring 1998 

[ Home | Lecture Notes| WebTutor | WebTutor Site Map]


Linked Lists: Part I

You need to understand pointers before studying this material.
For information on pointers, click here.


Linked Lists

Initialize current to first node
while (list is not done) {
   Display the data in the current position
   move to next in list
}

 


// Chap 4, p 154

struct node;
typedef struct node* ptrType;
struct node {
   int Data;
   ptrType Next;
};

void DisplayList(ptrType Head)
// --------------------------------------------------------------
// Displays the data in a linked list.
// Precondition: Head is a pointer variable that points to
// the linked list.
// Postcondition: Displays the data in the linked list.
// Both Head and the list are unchanged.
// --------------------------------------------------------------
{
   // Loop invariant: Cur points to the next node to be displayed
   for (ptrType Cur = Head; Cur != NULL; Cur = Cur->Next)
   cout << Cur->Data << "\n";
} // end DisplayList


Deleting a Node

Prev->Next = Cur->Next; // splices out current node
Cur->Next = NULL; // Defensive programming
delete Cur;
Cur = NULL; // Defensive programming

Does this work for special cases?
What are the special cases?


Inserting a Node

NewPtr = new node;
NewPtr->Item = 8;
NewPtr->Next = Cur;
Prev->Next = NewPtr;

// Are these statements order dependent?

// What are the special cases?


Copyright chris wild 1998.
For problems or questions regarding this web contact [Dr. Wild (e-mail:wild@cs.odu.edu].
Last updated: April 08, 1998.