Java实现单链表的头插尾插、头删尾删

构造一个简单的单链表类

public class MyLinkedList {
    /**
     * 链表中的一个结点
     */
    public class Node {
        public int value;   // 保存的是有效数据
        public Node next;   // 下一个结点的线索(引用)

        Node(int v) {
            this.value = v;
            this.next = null;
        }
    }

    // 如果一个结点都没有, head == null
    private Node head;      // 保存链表中第一个结点的引用

    MyLinkedList() {
        this.head = null;
    }
}

 尾插尾删需要遍历链表寻找节点,先写两个方法:

遍历寻找尾结点

private Node getLast() {
   Node cur = this.head;
    while (cur.next != null) {
      cur = cur.next;
    }
    return cur;
}

遍历寻找倒数第二个节点

private Node getPenult() {
   Node cur = this.head;
   while (cur.next.next != null) {
        cur = cur.next;
   }
   return cur;
}

头插

public void pushFront(int item) {
       Node node = new Node(item);
       node.next = this.head;
       this.head = node;
}

头删

        public void popFront() {
            if (this.head == null) {
                throw new Error("链表为空");
            }
            this.head = this.head.next;
        }

尾插

 public void pushBack(int item) {
       Node node = new Node(item);
       if (this.head == null) {
           this.head = node;
       } else {
          Node last = getLast();
          last.next = node;
       }
 }

尾删 

public void popBack() {
       if (this.head == null) {
           throw new Error("链表为空");
       }
       if (this.head.next == null) {
           this.head = null;
       } else {
           Node lastLast = getPenult();
           lastLast.next = null;
       }
}

其中,头插头删的时间复杂度为O(1),尾插尾删因为要遍历链表寻找节点,时间复杂度为O(n)。

发布了91 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42006733/article/details/104284381