CS 250 Computer Programming and Problem Solving - FALL 1998 

[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page ]


Linked Lists Review


 

Walking a Linked List

ll.gif (2350 bytes)

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

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

4-8.gif (4612 bytes)


 

Inserting a Node

4-12.gif (3907 bytes)

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

// Are these statements order dependent?

// What are the special cases?


 

Deleting a Node

4-9.gif (3715 bytes)

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?


 

Shallow vs Deep Copy

 

p166.gif (12908 bytes)


Copyright chris wild 1998.
For problems or questions regarding this website contact [Chris Wild (e-mail:wild@cs.odu.edu].
Last updated: October 19, 1998.