链表的操作,包括在链表的头,中间,尾增加和删除
package com.rao.linkList;
/**
* @author Srao
* @className LinkList
* @date 2019/12/3 10:39
* @package com.rao.linkList
* @Description
*/
public class LinkList {
/**
* 定义节点,下标从1开始
*/
static class Node{
public Integer data;
public Node next;
public Node(Integer data){
this.data = data;
}
}
//定义头节点
public Node head;
/**
* 用于初始化一个链表
* @param head
*/
public LinkList(Node head) {
this.head = head;
}
public LinkList() {
}
//根据 data 查找结点
public Node findNodeByData(Integer data){
Node currentNode = head;
while (currentNode != null && !currentNode.data.equals(data)){
currentNode = currentNode.next;
}
return currentNode;
}
//根据 index 查找结点
public Node findNodeByIndex(int index){
int num = 1;
Node currentNode = head;
while (currentNode != null && index != num){
currentNode = currentNode.next;
num++;
}
return currentNode;
}
//插入元素(指定元素向后插入)
public void insertNode(int index, Node node){
if (index == 0){
node.next = head;
head = node;
return;
}
Node currentNode = findNodeByIndex(index);
Node nextNode = currentNode.next;
currentNode.next = node;
node.next = nextNode;
}
//根据值删除结点
public void deleteNodeByData(Integer data){
Node currentNode = head;
Node preNode = null;
while (currentNode != null && !currentNode.data.equals(data)){
preNode = currentNode;
currentNode = currentNode.next;
}
if (preNode == null){//第一个命中
if (head.next != null){
head = head.next;
}else {
head = null;
}
}else if (currentNode == null){//最后一个命中
preNode.next = null;
}else {
preNode.next = currentNode.next;
}
}
public static void main(String[] args) {
LinkList linkList = new LinkList(new Node(100));
linkList.insertNode(1, new Node(3));
linkList.insertNode(1, new Node(4));
linkList.insertNode(1, new Node(5));//向中间插入
linkList.insertNode(0, new Node(20));//向头插入
linkList.insertNode(5, new Node(21));//向尾插入
System.out.println(linkList.findNodeByIndex(2).data);
System.out.println(linkList.findNodeByData(5).next.data);
System.out.println(linkList.findNodeByIndex(6).data);
linkList.deleteNodeByData(100);//删除中间节点节点
linkList.deleteNodeByData(20);//删除头节点节点
linkList.deleteNodeByData(21);//删除尾节点
System.out.println(linkList.head.data);
}
}
增加和删除一定要分情况讨论,写完代码之后也要对边界情况进行测试,只要思路理清楚了,写代码不是大问题