Data Structure.Linked List

链表成员

//建立结点 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();
    }
}

private Node dummyHead; //虚拟头结点
private int size;

构造链表

public LinkedList(){
    dummyHead = new Node(null, null); //携带信息 null 引用 null
    size = 0;
}

添加元素

//在链表中添加新元素 index=>索引
public void add(int index, E e){
	//对传入非法值的处理 抛出错误
    if (index < 0 || index > size){
        throw new IllegalArgumentException("Add failed. Illegal index.");
    }

    Node prev = dummyHead;
    for (int i = 0; i < index; i ++)
        prev = prev.next;
    prev.next = new Node(e, prev.next); //代码执行顺序 左 <- 右
	//维护元素个数
    size ++;
}

获取元素

//在链表中获得元素
public E get(int index){

    if (index < 0 || index >= size){
        throw new IllegalArgumentException("Get failed. Illegal index.");
    }

    Node cur = dummyHead.next;
    for (int i = 0; i < index; i ++)
        cur = cur.next;
    return cur.e;
}

修改元素

//在链表中修改新元素
public void set(int index, E e){

    if (index < 0 || index > size){
        throw new IllegalArgumentException("Set failed. Illegal index.");
    }

    Node cur = dummyHead.next;
    for (int i = 0; i < index; i ++)
        cur = cur.next;
    cur.e = e;
}

存在元素

//查找链表中是否存在元素
public boolean contains(E e){

    Node cur = dummyHead.next;
    while (cur != null){
        if (cur.e.equals(e))
            return true;
        else
            cur = cur.next;
    }
    return false;
}

删除元素

//删除链表某一元素
public E remove(int index){

    if (index < 0 || index >= size){
        throw new IllegalArgumentException("Remove failed. Illegal index.");
    }

    Node prev = dummyHead;
    for (int i = 0; i < index; i ++){
        prev = prev.next;
    }

    Node retNode = prev.next;
    prev.next = retNode.next;
    retNode.next = null; //触发回收机制
    size --; //维护元素个数

    return retNode.e;
}

输出格式

public String toString(){

    StringBuilder res = new StringBuilder();

    Node cur = dummyHead.next;
    while (cur != null){
        res.append(cur + "->");
        cur = cur.next;
    }
    res.append("END");

    return res.toString();
}

使用链表

public class Main {

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>(); //创建整型链表对象
}

猜你喜欢

转载自blog.csdn.net/weixin_43960884/article/details/88785900