大话数据结构—单链表(二)

1.链式结构

public class LinkedList {

    private Node head;
    private int size;

    public LinkedList() {
        head = null;
        size = 0;
    }

    public Object getElement(int i) {
        Node temp = head;
        int j = 0;
        while (temp != null && j < i) {
            temp = temp.next;
            j++;
        }
        if (temp == null || j > i) {
            return null;
        }
        return temp.data;
    }

    public void add(Object data) {
        if (head == null) {
            head = new Node(data);
            size++;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = new Node(data);
            size++;
        }

    }

    public boolean delete(int index) {
        if (size == 0) {
            return false;
        }
        Node previous = head;
        Node current = head;
        int j = 0;
        while (current != null && j < index) {
            previous = current;
            current = current.next;
            j++;
        }
        if (current == null || j > index) {
            return false;
        }
        previous.next = current.next;
        current.next = null;
        size--;
        return true;
    }

    public void display() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data);
            temp = temp.next;
        }
        System.out.println("---------------");
    }

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        linkedList.display();

        linkedList.delete(1);
        linkedList.display();

        System.out.println(linkedList.getElement(2));
        System.out.println(linkedList.getElement(5));
        
    }

}

class Node {
    Object data;
    Node next;

    public Node(Object data) {
        this.data = data;
        this.next = null;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。