import java.util.*;
class Node{
int val;//data|element
Node next;//如果next==null表示是最后一个结点
Node(int val){
this.val=val;
this.next=null;
}
public String toString() {
return String.format("Node(%d)",val);
}
}
public class MyLinkedList {
public static void main(String[] args) {
Node head=null;//head的意思是链表的第一个结点
//通过第一个结点,就可以找到完整的链表
//所以,链表的第一个结点往往代表整个链表
//空的链表,就是一个结点都没有的链表,也就没有第一个结点
head=pushFront(head,1);
head=pushFront(head,2);
head=pushFront(head,3);
print(head);
}
//head是原来的第一个结点 val是要插入的值 返回是新的第一个节点
public static Node pushFront(Node head,int val){
Node node=new Node(val);//结点
node.next=head;//让原来的head成为node的下一个结点
//head=node;//更新第一个节点的引用
return node;
}//头插
private static void print(Node head) {
for(Node cur=head;cur!=null;cur=cur.next) {
System.out.println(cur);
}
}//链表的打印
private Node popFront(Node head) {
if(head==null) {
System.err.println("空链表无法作删除");
return;
}
//原来第一个结点,会因为没有引用指向而被回收
return head.next;
}//头删
private Node popBack(Node head) {
if(head==null) {
System.err.println("空链表无法删除");
return;
}
if(head.next==null) {
return null;
}
else {
Node lastSecond=head;
while(lastSecond.next.next!=null) {
lastSecond=lastSecond.next;
}
lastSecond.next=null;
}
}//尾删
private static Node pushBack(Node head,int val) {
Node node=new Node(val);
if(head==null) {
return node;
}
else {
Node last=head;
while(last.next!=null) {
last=last.next;
}
last.next=node;
return head;
}
}//尾插
}
java中链表的一些简单实现方法
最新推荐文章于 2023-07-26 12:51:05 发布
本文详细介绍了使用Java实现链表的基本操作,包括头插法、尾插法、头删法和尾删法,并提供了完整的代码示例。通过本文,读者可以深入理解链表的数据结构及其在Java中的具体实现。
1749

被折叠的 条评论
为什么被折叠?



