list接口,定义了线性表的长度,判空,插入,删除,获取
package list;
public interface List {
public int size();
public boolean isEmpty();
public void insert(int index,Object obj) throws Exception;
public void delete(int index) throws Exception;
public Object get(int index) throws Exception;
}
定义了结点,一个是要存储的数据和一个指向(指向下一个结点)
package list;
public class Node {
Object data;//要存储的数据
Node next;//指向下一个结点
public Node(Object data) {
super();
this.data = data;
}
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Node() {
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
单链表的实现
package list;
public class LinkedList implements List {
private int size;//结点总数
private Node head = new Node();//头结点,不存储数据,只为编程方便
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void insert(int index, Object obj) throws Exception {
Node p = head;
for(int i = 0; i < index; i++)
{
p = p.next;
}
Node p1 = new Node();
p1.data = obj;
p1.next = p.next;
p.next = p1;
size++;
}
@Override
public void delete(int index) throws Exception {
Node p = head;
for(int i = 0; i < index; i++)
{
p = p.next;
}
p.next = p.next.next;
size--;
}
@Override
public Object get(int index) throws Exception {
Node p = head;
for(int i = 0; i <= index; i++)
{
p = p.next;
}
return p.data;
}
}
测试类(主要是增删查)
package list;
public class LinkedListTest {
public static void main(String[] args) {
LinkedList list = new LinkedList();
try {
list.insert(0, 0);
list.insert(1, 1);
list.insert(2, 2);
list.insert(3, 3);
list.insert(4, 4);
list.insert(5, 5);
list.insert(6, 6);
list.insert(7, 7);
for(int i = 0; i < list.size();i++)
{
System.out.println("第"+i+"个元素为"+list.get(i));
}
list.delete(0);
System.out.println("------------------------------");
for(int i = 0; i < list.size();i++)
{
System.out.println("第"+i+"个元素为"+list.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}