/**
* 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;
}
}
}