GenericList.java
package my;
public class GenericList
{
// 通用節點類型
public static class GenericNode
{
public Object value; // 該節點的數據
public GenericNode next; // 下一個節點
}
// 有頭鏈表: 固定的頭節點,頭節點裏不含有效數據
public GenericNode head = new GenericNode();
// 添加一個對象
public void add ( Object value )
{
// 找到末節點
GenericNode tail = head;
while( tail.next != null)
tail = tail.next;
// 附加到末尾
GenericNode node = new GenericNode ();
node.value = value;
tail.next = node;
}
// 查找節點並刪除, 如果有多個相同節點,則一併刪除
public void remove(Object value)
{
GenericNode node = head;
while(node.next != null)
{
if(node.next.value.equals(value)) // 用equals方法進行比較
node.next = node.next.next;
else
node = node.next;
}
}
// 長度
public int size()
{
int count = 0;
GenericNode m = head.next;
while( m != null)
{
count += 1;
m = m.next;
}
return count;
}
}
Student.java
package my;
public class Student
{
public int id;
public String name;
public String phone;
public Student()
{
}
public Student(int id, String name, String phone)
{
this.id = id;
this.name = name;
this.phone = phone;
}
@Override
public String toString()
{
return String.format("學生(%d, %s, %s)", id, name, phone);
}
}
Test1.java
package my;
import java.util.Iterator;
import java.util.LinkedList;
public class Test1
{
// Java API裏的 LinkedList 或 ArrayList 表示鏈表
public static void main(String[] args)
{
LinkedList<Student> list = new LinkedList<Student>();
list.add( new Student(1, "shao", "13810012345"));
list.add( new Student(2, "wang", "15290908889"));
list.add( new Student(3, "li", "13499230340"));
Iterator<Student> iter = list.iterator();
while(iter.hasNext())
{
Student d = iter.next();
System.out.println(d);
}
}
}
Test2.java
package my;
import my.GenericList.GenericNode;
public class Test2
{
public static void main(String[] args)
{
// GenericList: 自定義的鏈表類
GenericList list1 = new GenericList();
list1.add( new Student(1, "shao", "13810012345"));
list1.add( new Student(2, "wang", "15290908889"));
list1.add( new Student(3, "li", "13499230340"));
// 取得首節點
GenericNode node = list1.head.next;
while(node != null)
{
Student s = (Student)node.value;
System.out.println(s);
node = node.next;
}
}
}