赞
踩
使用Java语言实现了单链表,包括基本的增删改查。
- /**
- * 链表类
- * 1、包含一个存储内容为空的头结点指针;
- * 2、索引为0-index
- * @author Haigp
- *
- * @param <T>
- */
- public class LinkedList<T> {
-
- public ListNode<T> head;
- public Integer total;
-
- // 创建单链表
- public LinkedList() {
- this.head = new ListNode<T>();
- this.total= 0;
- }
-
- // 求链表长度
- public int length() {
- // 空链直接返回
- if(this.head.next == null)return 0;
-
- // 遍历链
- int length = 0;
- ListNode<T> next = this.head.next;
- while(next!=null) {
- length++;
- next = next.next;
- }
- return length;
- }
-
- // 判空
- public boolean isEmpty() {
- return this.total == 0;
- }
-
- // 查找
- // 查找返回结点值为val的结点
- // 链表不能像数组一样进行随机访问,只能从头结点head开始,逐个的往后遍历。时间复杂度为O(n)
- public ListNode<T> find(T val){
- ListNode<T> node = this.head.next;
- while(node!=null) {
- if(node.val == val)return node;
- else node = node.next

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。