//定义链表的结点类
class Node{
public Node next;//下一个结点
public String data;//数据
public Node(String data){
this.data = data;
}
//显示结点
public void show(){
System.out.print(data + " ");
}
}
//定义链表类及其操作方法
class LinkedList{
public Node head;//定义头结点
public int location = 0;//结点的位置
//头插
public void addHeadNode(String data){
Node node = new Node(data);
node.next = head;
head = node;
}
//头删,并返回头结点,返回之前的头结点
public Node deleteHeadNode(){
Node tempNode = head;
head = tempNode.next;
return tempNode;
}
//在任意位置插入结点,在index后面插入
public void insert(int index,String data){
Node node = new Node(data);
Node curNode = head;
Node previousNode = head;
while(index != location){
previousNode = curNode;
curNode = curNode.next;
location++;
}
node.next = curNode;//!!!!!
previousNode.next = node;//!!!!!
location = 0;
}
//查找任意位置的结点
public Node findByLocation(int index){
Node curNode = head;
while(index != location){
curNode = curNode.next;
location++;
}
return curNode;
}
//删除任意位置的结点
public Node deleteByLocation(int index){
Node curNode = head;
Node previousNode = head;
while(index != location){
previousNode = curNode;
curNode = curNode.next;
location++;
}
if(curNode == head){
head = head.next;
}else{
location = 0;
previousNode.next = curNode.next;
}
return curNode;
}
//根据数据查找结点信息
public Node findByData(String data){
Node curNode = head;
while(data != curNode.data){
curNode = curNode.next;
}
return curNode;
}
//根据结点的data删除结点(仅仅删除第一个)
public Node deleteByData(String data){
Node curNode = head;
Node previousNode = head;
while(data != curNode.data){
if(curNode.next == null){
return null;
}
previousNode = curNode;
curNode = curNode.next;
}
if(curNode == head){
head = head.next;
}else{
previousNode.next = curNode.next;
}
return curNode;
}
//显示所有结点信息
public void displayAllNodes(){
Node curNode = head;
while(curNode != null){
curNode.show();
curNode = curNode.next;
}
System.out.println();
}
}
public class Link {
public static void main(String[] args){
LinkedList linkedList = new LinkedList();
linkedList.addHeadNode("A");
linkedList.addHeadNode("B");
linkedList.addHeadNode("C");
linkedList.insert(1, "D");
linkedList.insert(2, "E");
linkedList.insert(3, "F");
linkedList.displayAllNodes();
Node node1 = linkedList.deleteByData("A");
System.out.println("node:" + node1.data);
linkedList.displayAllNodes();
Node node2 = linkedList.findByLocation(0);
System.out.println("node:" + node2.data);
Node node3 = linkedList.findByData("E");
System.out.println("node:" + node3.data);
}
}
运行结果:
C D E F B A
node:A
C D E F B
node:C
node:E