单链表的实现
class Node {
public int data;
public Node next;
public Node(int data){
this.data = data;
}
}
class MyLinkList {
public Node head;
public MyLinkList(){
this.head = null;
}
public void addFirst(int data){
Node node = new Node(data);
if(head == null){
head = node;
head.next = null;
return ;
}else {
node.next = head;
head = node;
}
}
public void addLast(int data){
Node node = new Node(data);
Node cur = this.head;
if(head == null){
head = node;
head.next = null;
return ;
}
while(cur.next != null){
cur = cur.next;
}
cur.next = node;
node.next = null;
}
private void checkIndex(int index){
if(index < 0 || index > size()){
throw new IndexOutOfBoundsException("Index越界");
}
}
private Node foundIndex(int index){
Node cur = this.head;
int count = 0;
while(cur != null && count < index-1){
cur = cur.next;
count++;
}
return cur;
}
public boolean addIndex(int index,int data){
checkIndex(index);
Node cur = foundIndex(index);
Node node = new Node(data);
if(index == 0){
addFirst(data);
return true;
}
else if(index == size()){
addLast(data);
return true;
} else{
node.next = cur.next;
cur.next = node;
return true;
}
}
public boolean contains(int key){
Node cur = this.head;
while(cur != null){
if(cur.data == key){
return true;
}
cur = cur.next;
}
return false;
}
public void remove(int key){
Node cur = this.head;
while(cur != null && cur.next != null){
if(cur.data == key && cur == head){
head = cur.next;
return;
}
else if(cur.next.data == key){
cur.next = cur.next.next;
return;
}
cur = cur.next;
}
}
public void removeAllKey(int key){
Node cur = this.head;
while(cur != null && cur.next != null){
if(cur.data == key && cur == head){
head = cur.next;
}
else if(cur.next.data == key){
cur.next = cur.next.next;
}
cur = cur.next;
}
}
public int size(){
Node cur = this.head;
int count = 0;
if(head == null){
return 0;
}
while(cur != null){
count++;
cur = cur.next;
}
return count;
}
public void display(){
Node cur = this.head;
while(cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
public void clear(){
this.head = null;
}
}
测试
public class Text {
public static void main(String[] args) {
MyLinkList myLinkList = new MyLinkList();
myLinkList.addFirst(1);
myLinkList.addFirst(2);
myLinkList.addFirst(3);
myLinkList.addFirst(3);
myLinkList.addLast(5);
myLinkList.display();
System.out.println("长度:"+myLinkList.size());
myLinkList.addIndex(3,4);
myLinkList.display();
myLinkList.remove(4);
myLinkList.display();
myLinkList.removeAllKey(3);
myLinkList.display();
System.out.println("清空单链表====");
myLinkList.clear();
myLinkList.display();
System.out.println("清空单链表====");
}
}
测试结果
3 3 2 1 5
长度:5
3 3 2 4 1 5
3 3 2 1 5
2 1 5
清空单链表====
清空单链表====