单向链表
- 链表是以节点的方式来存储的,是链式存储
- 每个节点包含一个数据域用来保存当前节点的数据,一个next域用于指向下一个节点
单链表结构示意图:

单链表内存示意图:

代码实现:
class Link{
private Node head;
private Node tail;
private int size;
private class Node{
public Object value;
public Node next;
private Node(Object value) {
this.value=value;
}
}
public void add(Object obj){
Node temp = new Node(obj);
if(head==null){
tail=head=temp;
}else{
tail=tail.next=temp;
}
size++;
}
public void travel(){
Node temp = this.head;
while(temp!=null){
System.out.print(temp.value+" ");
temp=temp.next;
}
System.out.println();
}
public int size(){
return size;
}
public boolean remove(Object val) {
if (this.head == null) {
return false;
}
if(head.value.equals(val)) {
head = head.next;
if(head.next==null){
tail=null;
}
--size;
return true;
}
Node temp = head;
while (temp.next!=null){
if(temp.next.value.equals(val)){
if(temp.next.next==null){
this.tail=temp;
}
temp.next=temp.next.next;
--size;
return true;
}
temp=temp.next;
}
return false;
}
public boolean modify(int index,Object obj){
if(index<0||index>this.size()-1) {
return false;
}
int count=0;
Node temp = this.head;
while(temp!=null) {
if (index == count) {
temp.value = obj;
}
temp = temp.next;
count++;
}
return true;
}
public Object selectOne(int index){
Node temp = this.head;
int count=0;
while(temp!=null) {
if (index == count) {
return temp.value;
}
temp = temp.next;
count++;
}
return null;
}
}
public class LinkTest {
public static void main(String[] args) {
Link link = new Link();
link.add(40.5f);
link.add(20);
link.add(40.5);
link.add(4653453453L);
link.add(-564);
link.add('A');
link.add((byte)127);
link.travel();
System.out.println(link.size());
link.remove(40.5);
link.remove(40.5f);
link.travel();
System.out.println(link.size());
}
}