单向链表-java实现

/**
 * Copyright (C), 2018-2019, LMaWC
 * FileName: LinkList
 * Author:   neo
 * Date:     2019/7/27 22:46
 * Description: 单向链表
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.linkList;

/**
 * 〈一句话功能简述〉<br> 
 * 〈单向链表〉
 *
 * @author neo
 * @create 2019/7/27
 * @since 1.0.0
 */
public class LinkList {
    // 定义头指针
    Node head = null;

    // 返回节点的长度
    public int listLength(){
        Node temp = head;
        int count = 0;
        while (temp != null){
            count++;
            temp = temp.next;
        }
        return count;
    }

    //添加节点
    public void add(int data){
        // 首次添加首节点
        if(head == null){
            head= new Node(data);
            return;
        }
        // 添加其他节点
        Node temp = head;
        while (temp.next!=null){
            temp =temp.next;
        }
        temp.next = new Node(data);
    }

    // 删除指定位置的节点(这里没有头节点)
    public boolean deleteNodeWithIndex(int index){
        // 首先判定index是否在指定的位置
        if(index<1 || index >listLength()){
            return false;
        }

        // 删除的是首节点要特殊处理(重点)
        if(index ==1){
            head = head.next;
            return true;
        }
        Node cur = head;
        Node preNode = head;
        int num = 1;
        while (cur != null){
            if(num == index){
                preNode.next = cur.next;
                return true;
            }
            preNode = cur;
            cur =cur.next;
            num++;
        }
        return false;

    }

    // 删除指定数据的节点------使用头结点遍历的方式
    public boolean deleteNode(int data){
        // 链表为空,无法删除
        if(head == null){
            return false;
        }
        // 如果删除的是首节点,要特殊处理
        if(head.data ==data){
            head = head.next;
            return true;
        }
        Node cur = head;
        Node preNode =head;
        while (cur !=null){
            if(cur.data == data){
                preNode.next = cur.next;
                return true;
            }
            preNode = cur;
            cur = cur.next;
        }
        return false;
    }
    
    // 打印整个链表
    public void printList(){
        Node temp = head;
        while (temp!=null){
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    // 定义节点
    class Node{
        // 指针域
        Node next = null;
        // 数据域(为了简化,使用了整型数据)
        int data;
        // 构造函数
        public Node(int data){
            this.data =data;
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值