1.链表定义
/**
* @Author:hemingzhu
* @date: 2020/1/21 10:29
* @Explanation:
*/
public class OneNode {
private OneNode node;
private int data;
public OneNode(OneNode node, int data) {
this.node = node;
this.data = data;
}
public OneNode() {
}
public OneNode(int data) {
this.data = data;
}
public OneNode getNode() {
return node;
}
public void setNode(OneNode node) {
this.node = node;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
2.基本操作
/**
* @Author:hemingzhu
* @date: 2020/1/21 10:29
* @Explanation:
*/
public class OneLike {
private OneNode root;
//插入
public void insert(int data){
OneNode node = new OneNode(data);
if(root == null){
root=node;
return;
}else{
OneNode oneNode = root;
while (oneNode.getNode() != null){
oneNode = oneNode.getNode();
}
oneNode.setNode(node);
}
}
//查询
public void select(){
OneNode oneNode = root;
while (oneNode != null){
System.out.println(oneNode.getData());
oneNode = oneNode.getNode();
}
}
//排序 小-》大
public void sort(){
OneNode node1 = root;
//最小的node
OneNode minOndeNode = new OneNode(root.getData());
OneNode node2 = null;
while (node1 != null){
int a = node1.getData();
if(a < minOndeNode.getData() ){
OneNode node3 = new OneNode(node1.getData());
if(node2==null){
node2 = new OneNode(node1.getData());
}else{
node3.setNode(node2);
node2 = node3;
}
minOndeNode = node3;
}else{
if(node2 == null){
node2 = new OneNode(minOndeNode.getData());
}else{
OneNode node3 = new OneNode(node1.getData());
OneNode node4 = node2;
while(node4.getNode()!=null){
node4 = node4.getNode();
}
node4.setNode(node3);
}
}
node1 = node1.getNode();
}
while (node2 != null){
System.out.println(node2.getData());
node2 = node2.getNode();
}
}
//长度
public int length(){
int i = 0 ;
OneNode node = root;
while (node != null){
i++;
node = node.getNode();
}
return i;
}
//删除,删除第i个数据
public boolean remove(int index){
int i = 0;
if(index<0){
return false;
}
if(index == 0){
root = root.getNode();
}
OneNode node = root;
while (node.getNode()!=null){
if(i == index-1){
node.setNode(node.getNode().getNode());
return true;
}else{
i++;
node = node.getNode();
}
}
return false;
}
public static void main(String[] args) {
OneLike oneLike = new OneLike();
oneLike.insert(5);
oneLike.insert(6);
oneLike.insert(7);
oneLike.insert(2);
oneLike.insert(9);
oneLike.insert(1);
oneLike.insert(0);
oneLike.insert(-1);
oneLike.select();
System.out.println("---------------------------");
oneLike.remove(1);
oneLike.select();
// System.out.println("---------------------------");
// oneLike.sort();
// System.out.println("-----------------------------");
// System.out.println(oneLike.length());
// System.out.println("--------------------------------");
}
}