链表的定义和创建
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表中的每一个元素如下图所示的结构:
链表的节点在java中的定义方式:
static class Node {
public int val;
public Node next;
Node(int x) {
val = x;
next = null;
}
}
链表的增删改查
1.增
public static Node toucha(Node head,Node insertNode){
if(head == null){
insertNode = head;
}else{
insertNode.next = head.next;
head.next = insertNode;
}
return head;
}
public static Node weicha(Node head,Node insertNode){
if(head == null){
insertNode = head;
}else{
Node cur = head;
while(cur.next!=null){
cur = cur.next;
}
cur.next = insertNode;
}
return head;
}
上述代码分别为头插法和尾插法
2.删
public static void delete(Node head,int val){
if(head == null){
return;
}else{
Node cur = head;
while(cur.next.data == val){
cur = cur.next;
}
cur.next = cur.next.next;
}
}
3.改
public static void modify(Node head,int position,int val){
if(head == null){
return;
}else{
int count = 1;
Node cur = head;
while(count != position){
count++;
cur = cur.next;
}
cur.data = val;
}
}
4.查``
public static int check(Node head,int position){
if(head == null){
return 0;
}else{
int count = 1;
Node cur = head;
while(count != position){
count++;
cur = cur.next;
}
return cur.data;
}
}
注意,上述的增删改查只是最基本的实现,并没有考虑越界以及空指针的问题。