【Java】链表的打印,添加,反转,删除。

本文详细介绍了一个使用Java实现的链表类,包括头插法、尾插法、删除节点、链表反转等基本操作,并提供了完整的代码示例。通过本文,读者可以深入理解链表的数据结构及其常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package edu;

import org.junit.Test;

class Node{
    public int val;
    public Node next =null;
    public Node(int val){
        this.val=val;
    }
}
public class Testaaa {
    public static void display(Node head){
        for(Node a=head;a!=null;a=a.next){
            System.out.print("("+a.val+")->");
        }
        System.out.print("null");
        System.out.printf("%n");
    }
    public static Node pushFront(Node head,int val) {//头插
        Node newnode=new Node(val);
        newnode.next=head;
        return newnode;
    }
    public static Node pushBack(Node head,int val) {//尾插
        if(head==null) {
            return pushFront(head,val);
        }else {
            Node newnode=new Node(val);
            Node last=getlast(head);
            last.next=newnode;

        }
        return head;
    }
    public static Node getlast(Node head) {
        Node a=head;
        while(a.next!=null) {
            a=a.next;
        }
        return a;
    }
    public static Node reverseList(Node head) {//链表反转
        Node newList=null;
        Node a=head;
        while(a!=null) {
            Node next=a.next;
            a.next=newList;
            newList=a;
            a=next;
        }
        return newList;
    }
    public static Node remove(Node head,int val) {//删除
        Node newlist=null;
        Node a=head;
        while(a!=null) {
            Node next=a.next;
            Node last=null;
            if(a.val!=val) {
                if(newlist==null) {
                    a.next=newlist;
                    newlist=a ;
                }else {
                    last=newlist;
                    while(last.next!=null) {
                        last=last.next;
                    }
                    last.next=a;
                    a.next=null;
                }
            }
            a=next;
        }
        return newlist;
    }

    public static void main(String[] args) {
     Node head=null;
        head = pushFront(head, 10);
        head = pushFront(head, 11);
        head = pushFront(head, 12);
        display(head);
        head=pushBack(head,13);
        head=pushBack(head,14);
        display(head);
        head=remove(head,14);
        display(head);
        head=reverseList(head);
        display(head);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值