单向链表
- 链表是以节点的方式来存储的,是链式存储
- 每个节点包含一个数据域用来保存当前节点的数据,一个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;
}
//如果要删除的节点是头节点,就把head指向第二个节点
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)){
//如果要删除的是最后一个节点,就把尾节点指向temp
if(temp.next.next==null){
//temp.next=null;
this.tail=temp;
}
//如果删除的是中间节点,就把当前节点上一个节点的next指向当前节点的下一个节点
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());
}
}