链表
链表如果不计查找算法的时间来说,其余操作时间复杂为O(1)
数据结构 | 数组 | 链表 |
---|
增加 | O(n) | O(1) | 删除 | O(n) | O(1) | 修改 | O(1) | O(1) | 查询 | O(1) | O(n) |
链表节点
Node.java
package SuanFa.链表;
public class Node {
int val;
Node next;
public Node(){
}
public Node(int val){
this.val = val;
}
}
链表的增删改查
MyLinkedList.java
public class MyLinkedList {
private Node head;
private Node last;
private int size;
public Node get(int index){
if(index<0 || index>=size){
System.out.println("===下标超出链表范围===");
return null;
}else {
Node temp = head;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp;
}
}
public void insert(int index,int val){
if(index<0 || index>size){
System.out.println("===下标超出链表范围===");
}else {
Node newNode = new Node(val);
if (size == 0) {
head = newNode;
last = newNode;
} else if (index == 0) {
newNode.next = head;
head = newNode;
} else if (index == size) {
last.next = newNode;
last = newNode;
} else {
Node prevIndex = get(index - 1);
newNode.next = prevIndex.next;
prevIndex.next = newNode;
}
size++;
}
}
public Node delete(int index){
if(index<0 || index>=size){
System.out.println("===下标超出链表范围===");
return null;
}else{
Node deleteNode = new Node();
if(index == 0){
deleteNode = head;
head = head.next;
}else if(index == size-1){
Node prevNode = get(index-1);
deleteNode = prevNode.next;
prevNode.next = null;
last = prevNode;
}else{
Node prevNode = get(index-1);
deleteNode = prevNode.next;
prevNode.next = prevNode.next.next;
}
return deleteNode;
}
}
public boolean update(int index,int upVal){
if(index<0 || index>=size){
System.out.println("===下标超出链表范围===");
return false;
}else{
if(index == 0){
head.val = upVal;
}else if(index == size-1){
last.val = upVal;
}else{
Node updateNode = get(index);
updateNode.val = upVal;
}
}
return true;
}
public void print(){
Node temp = head;
while(temp!=null){
System.out.print(temp.val+" ");
temp = temp.next;
}
}
}
链表测试类
MyLinkedListDemo.java
public class MyLinkedListDemo {
public static void main(String[] args) {
MyLinkedList mll = new MyLinkedList();
Node node = mll.get(0);
System.out.println(node);
mll.insert(0,2);
mll.insert(1,3);
mll.insert(2,4);
mll.insert(1,6);
System.out.println(mll.get(2).val);
mll.print();
System.out.println();
System.out.println(mll.delete(2).val);
mll.print();
System.out.println();
mll.update(1,5);
mll.print();
}
}
链表和数组的区别
各有春秋,主要看运用环境,如果需要读操作多,写(增删改)操作少的话建议用数组;相反则用链表比较灵活
|