Skip to content

Instantly share code, notes, and snippets.

@Illvili
Created May 4, 2015 03:51
Show Gist options
  • Save Illvili/d53a40f081f81d92e349 to your computer and use it in GitHub Desktop.
Save Illvili/d53a40f081f81d92e349 to your computer and use it in GitHub Desktop.
public class DVD {
public String Title;
public DVD(String t) {
this.Title = t;
}
}
public class DVDCollection {
public static void main(String[] args) {
DVD d1 = new DVD("musicalExample");
DVD d2 = new DVD("romanceExample");
DVD d3 = new DVD("horrorExample");
DVD d4 = new DVD("documentaryExample");
DVD d5 = new DVD("dramaExample");
DVD d6 = new DVD("comedyExample");
DVDList dl = new DVDList();
dl.SearchAndInsert(d1);
dl.SearchAndInsert(d2);
dl.SearchAndInsert(d3);
dl.SearchAndInsert(d4);
dl.SearchAndInsert(d5);
dl.SearchAndInsert(d6);
dl.PrintDebug();
}
}
public class DVDList {
public class DVDListNode {
public DVD Data;
public DVDListNode Next;
public DVDListNode(DVD data) {
this.Data = data;
this.Next = null;
}
public DVDListNode(DVD data, DVDListNode next) {
this.Data = data;
this.Next = next;
}
}
public DVDListNode HEAD;
public int Count = 0;
public void PrintDebug() {
if (0 == this.Count) {
System.out.println("There is no DVD in list");
} else {
System.out.println("DVD in list:\n==========");
DVDListNode cur = this.HEAD;
do {
System.out.println(cur.Data.Title);
} while (null != (cur = cur.Next));
System.out.print("==========\nTotal: ");
System.out.println(this.Count);
}
}
public void SearchAndInsert(DVD newDvd) {
if (null == this.HEAD) {
this.HEAD = new DVDListNode(newDvd);
this.Count = 1;
return ;
}
// search position
DVDListNode cur = this.HEAD, prev = null;
do {
int compareResult = cur.Data.Title.compareTo(newDvd.Title);
if (compareResult > 0) {
DVDListNode node = new DVDListNode(newDvd, cur);
if (null == prev) {
// cur is HEAD
this.HEAD = node;
} else {
prev.Next = node;
}
this.Count++;
return ;
}
prev = cur;
cur = cur.Next;
} while (null != cur);
// newDvd is last
prev.Next = new DVDListNode(newDvd);
this.Count++;
}
}
DVD in list:
==========
comedyExample
documentaryExample
dramaExample
horrorExample
musicalExample
romanceExample
==========
Total: 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment