实现单链表的基本操作

public class LinkedList {
    //定义数据类来存储结点信息
    class Node{
       private Node next = null;
       private int data;
        public Node(int data){
            this.data = data;
        }

    }
     Node head = null;// 链表头引用初始化为空

//  头插
 public void addFirst(int x){
     Node newNode = new Node(x);
     if (this.head == null){
         this.head = newNode;
     }else{
         newNode.next = head;
         this.head = newNode;
     }
 }
 //尾插
public void addLast(int y){
    Node newNode = new Node(y);
    Node cur = this.head;
    if (cur == null){
        cur = newNode;
    }else{
        while (cur.next != null){
            cur = cur.next;
        }
        cur.next = newNode;
    }
}
//打印链表
public void printList(){
    Node tem = head;
    while (tem != null){
        System.out.print(tem.data);
        tem = tem.next;
    }

}
//获取长度
public int size(){
    Node cur = this.head;
    int count = 0;
    while(cur != null){
        cur = cur.next;
        count++;
    }
    return count;
}

//删除index后一个位置的节点
public void deleteNode(int index) {
    if(index == 1 ){
        System.out.println("删除位置不合法!");
        return;
    }
    Node cur = this.head;
    int length = 0;

    while(cur.next != null){
        length++;

        if(length == index){
            cur.next = cur.next.next;
            return;
        }
        cur = cur.next;

    }

}
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.addFirst(9);
        list.addFirst(5);
        list.addFirst(2);
        list.addFirst(7);

        System.out.print("头插之后:");
        list.printList();
        System.out.println();
        list.addLast(9);
        list.addLast(5);
        list.addLast(2);
        list.addLast(7);
        System.out.print("尾插之后:");
        list.printList();
        System.out.println();
        list.deleteNode(3);
        System.out.print("删除第三个节点之后: ");
        list.printList();


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值