**
单链表的简单实现
**
package com.atguigu.javase.homeworl;
class Note {
int value;
Note nextNote; //作为向下指针
public Note(int value) {
this.value = value;
}
}
public class Link {
private Note head;// 首地址
private Note tail;// 尾部地址
public Note getHead() {
return head;
}
public Note getTail() {
return tail;
}
// 尾部增加单链表的方法
public void add(int value) { //在尾部插入
Note newNote = new Note(value);
if (head == null) {//判断是否存在链表
head = newNote;
tail = newNote;
} else { //如果存在则进行连接并且刷新尾部地址
tail.nextNote = newNote;
tail = tail.nextNote;
}
}
public void add(int value, int valu1) {// 在此value值后插入 value1
if (head == null) {//判断是否有数据
System.out.println("没有数据");
} else {
Note tmp = head;
while (tmp.value != value) {//当找到此value时跳出循环
tmp = tmp.nextNote;
if (tmp == null) {// 表示到达链表尾部也未找到 也跳出当前循环
System.out.println("没有数据");
return;
}
}
Note exchange = tmp.nextNote;
Note addNote = new Note(valu1);
//确定插入位置 改变相应的nextNote指向
tmp.nextNote = addNote;
addNote.nextNote = exchange;
}
}
public void delet(int value) {
if (head == null) {
System.out.println("没有数据");
} else {
if(head.value == value) {//删除头
head = head.nextNote;
}
Note tmp2 = head;
if(tmp2.nextNote==null) { //判断head后时都还有数据
System.out.println("无此数据");
return;
}
while (tmp2.nextNote.value != value) {//确定删除的是下一个Note
if( tmp2.nextNote.nextNote==null) {
System.out.println("无此数据");
return;
}
tmp2 = tmp2.nextNote;
}
Note tmp3 = tmp2.nextNote.nextNote;
tmp2.nextNote = tmp3;
}
}
public void toSay() { //遍历链表的value数据
if (head == null) {
System.out.println("未存任何数据");
return;
}
Note note = head;
while (note != null) {
System.out.println(note.value);
note = note.nextNote;
}
}
public int[] toArray() {//封装一个返回数组的链表方法 也可以在该类中定义一个计数器 在add方法和delete方法里完成增减
Note note = head;
int account = 0;//用于统计数据的个数即链表的长度
while (note != null) {
//System.out.println(note.value);
account++;
note = note.nextNote;
}
System.out.println(account);
int[] arr = new int[account];//创建数组用于接收链表的数据
int i = 0;
while (note != null) { //遍历链表数据依次写入数组
arr[i] = note.value;
i++;
note = note.nextNote;
}
return arr;
}
}
1331

被折叠的 条评论
为什么被折叠?



