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