数据结构-Java实现(三)
一、链表
1.1 概述
链表是真正动态的数据结构,最简单的动态数据结构,基本用于辅助组成其他数据结构。
数据存储在“节点”(Node)中
优点:真正的动态,不需要处理固定容量的问题
缺点:丧失了随机访问的能力
1.2 链表使用的基本功能
定义Node节点
private class Node{
public E e;
public Node next;
public Node(E e, Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null,null);
}
@Override
public String toString() {
return e.toString();
}
}
向链表中添加元素
具体代码实现:
//向链表中间添加元素
//在链表的index(0-based)位置添加新的元素e
public void add(int index, E e){
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed.Illeagl failed.");
Node prev = dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
// Node node = new Node(e);
// node.next = prev.next;
// prev.next = node;
prev.next = new Node(e, prev.next);
size++;
}
向链表中删除元素
具体代码实现:
//链表中删除index(0-based)位置的元素,返回删除的元素
public E remove(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed.Illeagl failed.");
Node pre = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
Node retNode = pre.next;
pre.next = retNode.next;
retNode.next = null;
size--;
return retNode.e;
}
链表功能的实现及测试类
public class LinkedList<E> {
private class Node{
public E e;
public Node next;
public Node(E e, Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null,null);
}
@Override
public String toString()