0%
前言
单向链表的Java版API实现
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| package com;
public class LinkList<T> {
private Node head; private int linkListLength;
private class Node {
public T item; public Node next;
public Node(T item, Node next) { this.item = item; this.next = next; }
}
public LinkList() { this.head = new Node(null, null); this.linkListLength = 0; }
public void clear() { head.next = null; linkListLength = 0; }
public int length() { return linkListLength; }
public boolean isEmpty() { return linkListLength==0; }
public T get(int index) { Node n = head; for (int i = 0; i < index; i++) { n = n.next; } return n.item; }
public void insert(T t) { Node n = head; while (n.next!=null) { n = n.next; } Node node = new Node(t, null); n.next = node; linkListLength++; }
public void insert(T t, int index) { Node nLeft = head; for (int i = 0; i < index-1; i ++) { nLeft = nLeft.next; } Node nRight = nLeft.next; Node node = new Node(t, null); nLeft.next = node; node.next = nRight; linkListLength++; }
public T remove(int index) { Node nLeft = head; for (int i = 0; i < index-1; i ++) { nLeft = nLeft.next; } Node nMiddle = nLeft.next; T t = nMiddle.item;
if (nMiddle.next==null) { nLeft.next = null; } else { nLeft.next = nMiddle.next; } linkListLength--; return t; }
public int indexOf(T t) { Node n = head; int index = 0; while (head.next!=null) { n = n.next; if (n.item.equals(t)) { return index; } index++; } return -1; }
public String toString() { String str = ""; Node n = head; while (n.next!=null) { n = n.next; str += n.item + " "; } return str; }
}
|
完成
参考文献
哔哩哔哩——黑马程序员