单链表Java代码实现
public class MyLinkedList<T> {
private Node mHead;
MyLinkedList() {
}
public void add(T data, int index) {
if (index < 0 || index > size()) {
throw new IllegalArgumentException("index is error");
}
if (index == 0) {
addHeadNode(data);
}
if (index == size()) {
addTailNode(data);
}
Node curNode = mHead;
int pos = 0;
Node preNode = null;
while (curNode.next != null) {
if (pos == index) {
Node node = new Node();
node.data = data;
node.next = preNode.next;
preNode.next = node;
}
pos++;
preNode = curNode;
curNode = curNode.next;
}
}
public int size() {
if (mHead == null) {
return 0;
}
if (mHead.next == null) {
return 1;
}
Node curNode = mHead;
int size = 0;
while (curNode.next != null) {
size++;
curNode = curNode.next;
}
return size;
}
public boolean delete(T value) {
if (size() == 0) {
return false;
}
if (mHead.data.equals(value)) {
mHead = mHead.next;
return true;
}
Node curNode = mHead;
while (curNode.next != null) {
if (curNode.next.data.equals(value)) {
curNode.next = curNode.next.next;
return true;
}
}
return false;
}
public T get(int i) {
if (mHead == null) {
return null;
}
Node curNode = mHead;
int pos = 0;
while (curNode.next != null) {
curNode = curNode.next;
pos++;
if (pos == i) {
return curNode.data;
}
}
return curNode.data;
}
/**
* 头插法
*
* @param value
*/
public void addHeadNode(T value) {
Node node = new Node(value);
if (mHead == null) {
mHead = node;
} else {
node.next = mHead;
mHead = node;
}
}
/**
* 尾插法
*
* @param value
*/
public void addTailNode(T value) {
Node node = new Node(value);
if (mHead == null) {
mHead = node;
} else {
Node last = mHead;
while (last.next != null) {
last = last.next;
}
last.next = node;
}
}
public Node reverse() {
if (null == mHead || null == mHead.next)
return mHead;
Node pre = mHead;
Node cur = mHead.next;
while (null != cur.next) {
Node tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
cur.next = pre;
mHead.next = null;
String s = cur.data.toString();
while (cur.next != null) {
cur = cur.next;
s += " " + cur.data.toString();
}
System.out.println( s);
return cur;
}
class Node {
T data;
Node next;
Node() {
}
public Node(T data) {
this.data = data;
this.next = null;
}
}
@NonNull
@Override
public String toString() {
if (mHead == null) {
return null;
}
String linkString = "";
Node curNode = mHead;
if (curNode.next == null) {
return curNode.data.toString();
}else {
while (curNode.next != null) {
linkString += " " + curNode.data.toString();
curNode = curNode.next;
}
linkString += " " + curNode.data.toString();
return linkString;
}
}
}