链表的操作

链表可以进行各种操作,例如头插,头删,尾插及尾删等,这些操作具体实现如下:

先用一个Node类来定义链表:

public class Node {
    int val;
    Node next;

    Node(int val, Node next){
        this.val=val;
        this.next=next;
    }
    
    Node (int val){
        this(val,null);
    }
    
    @Override
    public String toString(){
        return String.format("Null{%d}",val);
    }
}

实现头插:

public class MyLinkedList1 {
    Node head=null;
    Node last=null;
    int size=0;
    
    public Node pushFront(Node head, int val){
        head=new Node(val,head);
        size++;
        return head;
    }

头删:

public Node popFront(Node head){
        if(head==null){
            throw new RuntimeException("空了!");
        }
        head=head.next;
        size--;
        return head;
    }

尾插:

public void pushBack(Node head, int val){
        Node node =new Node(val);
        if(head==null){
            head=null;
        }else{
             last=head;
            while(last.next!=null){
              last  =last.next;
            }
            last.next=node;
            last=last.next;
            size++;
        }
    }

尾删:

 public void popBack(Node head){
            if(head==null){
                throw new RuntimeException("空了!");
            }else{
                Node prevlast=head;   //prev为倒数第二个结点
                while(prevlast.next.next!=null){
                    prevlast=prevlast.next;
                }
                prevlast.next=null;
                size--;
            }
    }

定义类去实现这些操作:

public class UseList1 {
    public static void print(Node head){
        Node cur=head;
        while(cur!=null){
            System.out.println(cur.val);
            cur=cur.next;
        }
    }

    public static void main(String[] args) {
        Node head=null;
        MyLinkedList1 h=new MyLinkedList1();
        head=h.pushFront(head,5);
        head=h.pushFront(head,4);
        head=h.pushFront(head,3);
        head=h.pushFront(head,2);
        head=h.pushFront(head,1);
        print(head);
        
        head=h.popFront(head);
        head=h.popFront(head);
        head=h.popFront(head);
        head=h.popFront(head);
        print(head);

        h.pushBack(head,4);
        h.pushBack(head,3);
        print(head);
        h.popBack(head);
        h.popBack(head);
        print(head);
    }
}

运行结果:
在这里插入图片描述
其中前五行为头插操作;
第五行为头删操作;
第6, 7, 8行为尾插操作;
第9行为尾删操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值