基于Java实现单链表的demo
package com.test.list; import java.util.Iterator; //基于Java实现单链表的demo public class linkedListDemoimplements Iterable { //头节点 private Node head; //链表的长度 private int L; //构造方法,初始化链表 public linkedListDemo() { head = new Node(null, null); L = 0; } //清空链表 public void clear() { this.head.next = null; this.head.item = null; L = 0; } //获取链表长度 public int getLength() { return L; } //判断链表是否为空 public boolean isEmpty() { return L == 0; } //获取指定位置的元素值 public T get(int i){ Node n = head.next; for (int j = 0; j < i; j++) { n = n.next; } return n.item; } //向链表添加元素,默认添加到最后的位置 public void insert(T t){ Node n = head; while(n.next!=null){ n = n.next; } Node newNode = new Node(t, null); n.next = newNode; L++; } //向链表指定位置添加元素 public void insert(T t,int i){ if(i<0 || i>= L){ throw new RuntimeException("位置不合法!!!"); } Node n = head; for (int j = 0; j <= i-1; j++) { n = n.next; } Node pre = n; Node current = n.next; Node newNode = new Node(t, current); pre.next = newNode; L++; } //删除指定位置的元素,并返回 public T remove(int i){ if(i<0 || i>= L){ throw new RuntimeException("位置不合法!!!"); } Node n = head; for (int j = 0; j <= i-1; j++) { n = n.next; } Node pre = n; Node current = n.next; Node currentNext = n.next.next; pre.next = currentNext; current.next = null; L--; return current.item; } //根据目标值,获取链表的第一次出现的下标 public int indexOfTarget(T t){ if(t == null){ throw new RuntimeException("参数不合法!"); } Node n = head.next; for (int i = 0; i < L-1; i++) { if(n.item.equals(t)){ return i; } n = n.next; } return -1; } //打印链表 public void printData(){ Node n = head.next; for (int i = 0; i < L; i++) { System.out.print("[" + i + "]=" + n.item + " "); n = n.next; } System.out.println(); } //节点类,用内部类演示 private class Node { //节点存储的数据 T item; //节点存储的下一个节点的地址 Node next; //构造方法 public Node(T item, Node next) { this.item = item; this.next = next; } } @Override public Iterator iterator() { return new LIterator(); } private class LIterator implements Iterator{ private Node n; public LIterator(){ this.n = head; } @Override public boolean hasNext() { return n.next!=null; } @Override public T next() { n = n.next; return n.item; } } }



