class Node{
public int value;
public Node next=null;
public Node(int value){
this.value=value;
}
}
public class CC{
public static Node pushFront(Node head, int value){
Node node=new Node(value);
node.next=head;
return node;
}
public static Node pushBack(Node head,int value){
Node node=new Node(value);
if(head==null){
node.next=head;
return node;
}
else{
Node last=getLast(head);
last.next=node;
return head;
}
}
public static void display(Node head){
for(Node cur=head;cur!=null;cur=cur.next){
System.out.printf("%d ->",cur.value);
}
System.out.println("null");
}
private static Node getLast(Node head){
Node last=head;
while(last.next!=null){
last=last.next;
}
return last;
}
public static void main(String[] args) {
Node head=null;
head = pushBack(head,1);
head = pushBack(head,2);
head = pushBack(head,3);
display(head);
head = pushFront(head,10);
head = pushFront(head,20);
head = pushFront(head,30);
display(head);
}
}
【Java】实现链的头插、尾插
最新推荐文章于 2025-09-24 17:38:28 发布
本文深入讲解了链表这一数据结构的实现与操作,包括节点的创建、链表的前插和后插操作,并通过具体代码示例展示了如何在链表头部和尾部插入元素,最后演示了链表的遍历过程。

784

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



