java模拟实现单向链表
直接上代码
1 package com.bjpowernode.test.datastructure; 2 3 public class Mylinked { 4 5 Node first;//头结点 6 7 int size;//链表的长度 8 9 public void add(Object value) { 10 Node newNode = new Node(value); 11 if (first == null) { 12 first = newNode; 13 } else { 14 Node tmp = first;//当前节点 15 while(tmp.getNext() != null) { 16 tmp = tmp.getNext(); 17 } 18 //设置最后一个元素的下一个引用 19 tmp.setNext(newNode); 20 } 21 size++; 22 } 23 24 public void add(Object value,int index) { 25 Node newNode = new Node(value); 26 if (index > size - 1) { 27 //插入链表最后的元素 28 add(value); 29 } else { 30 //在已有的元素之间插入 31 Node oldnode = first;//头节点,从头结点开始遍历,得到目标位置的元素,后面需要把新节点的next指向它 32 Node pre = first;//目标节点的上一节点 33 for (int i = 0; i < index; i++) { 34 if (i == index - 1) { 35 pre = oldnode; 36 } 37 oldnode = oldnode.getNext(); 38 } 39 //需要把上一个节点的next引用指向自己,自己的下一引用指向下一节点 40 pre.setNext(newNode); 41 newNode.setNext(oldnode); 42 size++; 43 } 44 } 45 public Object get(int index) { 46 Node tmp = first;//当前节点 47 for (int i = 0; i < index; i++) { 48 tmp = tmp.getNext(); 49 } 50 return tmp.getValue(); 51 } 52 public void remove(int index) { 53 if (index > size - 1) { 54 //没有节点 55 return; 56 } 57 if (index == 0) { 58 //删除头元素 59 first = first.getNext(); 60 } else { 61 //找到删除元素的头一个元素 62 Node tmp = first;//当前节点 63 for (int i = 0; i < index - 1; i++) { 64 tmp = tmp.getNext(); 65 } 66 tmp.setNext(tmp.getNext().getNext()); 67 size--; 68 } 69 } 70 public void remove(Object obj) { 71 if (size > 0) { 72 Node tmp = first; 73 int k = 0;//表示循环了几次才找到目标对象 74 while (!tmp.getValue().equals(obj)) { 75 tmp = tmp.getNext(); 76 k++; 77 } 78 if (size == 1) { 79 tmp = null; 80 } else { 81 Node node = tmp.getNext(); 82 //需要找到tmp的上一个节点 83 Node preNode = first; 84 for (int i = 1; i < k; i++) { 85 preNode = preNode.getNext(); 86 } 87 preNode.setNext(node); 88 } 89 size--; 90 } 91 92 } 93 class Node { 94 95 private Node next;//下一节点的引用 96 97 private Object value;//结点值 98 99 public void setNext(Node next) { 100 this.next = next; 101 } 102 103 public void setValue(Object value) { 104 this.value = value; 105 } 106 public Node(Object value) { 107 this.value = value; 108 } 109 110 public Node getNext() { 111 return next; 112 } 113 114 public Object getValue() { 115 return value; 116 } 117 } 118 119 int length() { 120 return size; 121 } 122 } 123 class Main { 124 125 public static void main(String[] args) throws Exception { 126 Mylinked mylinked = new Mylinked(); 127 mylinked.add("a"); 128 mylinked.add("b"); 129 mylinked.add("c"); 130 mylinked.add("d"); 131 mylinked.add("e"); 132 133 System.out.println(mylinked.get(0)); 134 System.out.println(mylinked.get(1)); 135 System.out.println(mylinked.get(2)); 136 System.out.println(mylinked.get(3)); 137 System.out.println(mylinked.get(4)); 138 mylinked.add("f", 2); 139 // mylinked.remove(5); 140 mylinked.remove("e"); 141 142 143 } 144 }