【Java实现】数据结构的部分源码记录

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;
		}	
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章