Docsity

A Trick to Simplify List Implementation - Notes | CMSC 132, Exams of Computer Science

Partial preview of the text

Download A Trick to Simplify List Implementation - Notes | CMSC 132 and more Exams Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

A Trick to Simplify List

Implementation

Department of Computer Science

University of Maryland, College Park

1

Typical List Implementation

Class List {

Node head;

Class Node {

Object value;

Node next;

2

Cool List Implementation Trick

You must practice this technique if you expect to use it

head is never null, even for an empty list

head is set to first node when list is created

head is never changed the value of the first node isn’t ever looked at

Class List { // value of first Node isn’t part of list final Node head = new Node(null); }

Insert in Front of i’th Element

void insertInFrontOf(int pos, Object value) {

Node after = head; for(int i = 0; i < pos; i++) after = after.next; Node newNode = new Node(value, after.next); after.next = newNode;

}