一、初始化
java
public class LinkedList {
public class ListNode{
int val = 0;
ListNode next = null;
public ListNode(int val){
this.val = val;
this.next = null;
}
}
private ListNode head;
private int size = 0;
public LinkedList(){
head = new ListNode(0);
this.size = 0;
}
}
二、头插
java
public void addFirst(int val){
ListNode newNode = new ListNode(val);
newNode.next = head.next;
head.next = newNode;
size++;
}
三、尾插
java
public void addLast(int val){
ListNode newNode = new ListNode(val);
ListNode cur = head;
while(cur.next != null){
cur = cur.next;
}
cur.next = newNode;
size++;
}
四、指定位置插入(下标)
java
public void addIndex(int index, int val){
if(index < 0 || index > size){
return;
}
ListNode newNode = new ListNode(val);
ListNode cur = head;
while(index-- > 0){
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
size++;
}
五、是否包含某个key
java
public boolean contains(int val){
ListNode cur = head.next;
while(cur != null){
if(cur.val == val){
return true;
}
cur = cur.next;
}
return false;
}
六、删除某个节点
java
public void remove(int val){
ListNode cur = head.next;
ListNode prev = head;
while(cur != null){
if(cur.val == val){
prev.next = cur.next;
size--;
break;
}
prev = cur;
cur = cur.next;
}
}
七、删除所有的key
java
public void removeAllKeys(int val){
ListNode cur = head;
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
}
八、size、打印、清理
java
public int size(){
return size;
}
public void display(){
ListNode cur = head.next;
while(cur != null){
System.out.print(cur.val + " ");
cur = cur.next;
}
}
public void clear(){
head.next = null;
size = 0;
}