单链表(SingleLinkedList)

发布时间 2023-11-22 14:59:09作者: MGLblog

单链表

1.创建一个Node类

//    head不能动,头节点作用是表示链表的头
    private Node head;
// 在linkedList类写一个Node的成员内部类
private class Node {
    private int data;
    private Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                '}';
    }
}

2.头插法

//    头插法
    public void addFirst(int data) {
//        首先创建一个节点,要头插的结点
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        newNode.next = head;
        head = newNode;
    }

3.尾插法

//    尾插法
public void addLast(int data) {
    //        首先创建一个节点
    Node newNode = new Node(data);
    if (head == null) {
        head = newNode;
        return;
    }
    //        head不能动,需要一个辅助指针temp,遍历完链表
    Node temp = head;
    while (temp.next != null) {
        temp = temp.next;//遍历链表
    }
    temp.next = newNode;
}

4.指定位置插入

//    指定位置插入
    public void addByOrder(int data, int position) {
        //        首先创建一个节点
        Node newNode = new Node(data);
        if (position == 0) {
//            头插法
            newNode.next = head;
            head = newNode;
            return;
        }
//        position是size的话就是尾插法
        if (position==size()){
            addLast(data);
            return;
        }
//        head不能动,需要一个辅助指针temp找的要插入位置的亲一个结点即temp
        Node temp = head;
        int curPosition = 0;
        while (temp.next != null && curPosition < position - 1) {
            temp = temp.next;
            curPosition++;
        }
        newNode.next = temp.next;
        temp.next = newNode;
    }

5.查找key是否在单链表中

//    查找key是否在单链表中
public boolean getKey(int key) {
    if (head.next == null) {
        System.out.println("链表为空~~~");
        return false;
    }
    Node temp = head.next;
    while (temp != null) {
        if (temp.data == key) {
            return true;
        }
        temp = temp.next;
    }
    return false;
}

6.链表长度

//    链表长度
public int size() {
    Node temp = head;
    int count = 0;
    while (temp != null) {
        count++;
        temp = temp.next;
    }
    return count;
}

7.删除数据