1.概念
*链表由多个节点对象组成,通过第一个节点对象去查找其他节点对象
*数据存储在节点中
*节点的结构:
***存储数据的变量
***存储下一个节点的变量
***设计一些存储其他信息的内容
2.创建链表
public class Node {
Object value;//链表存储的内容
Node next;//下一个节点
//实现链表输入与串联
public Node(Object value,Node next){
this.value=value;
this.next=next;
}
public static void main(String[] args){
Node node1 = new Node ("医生", null);
Node node2 = new Node ("预言家", null);
Node node3 = new Node ("狼人", null);
Node node4 = new Node ("巫师", null);
Node node5 = new Node ("平民", null);
Node node6 = new Node ("猎人", null);
Node node7 = new Node ("射手", null);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
node5.next=node6;
node6.next=node7;
Node first=node1;//首节点为node1
Node temp=first;
while(temp.next!=null){
System.out.print(temp.value+",");
temp=temp.next;
}
3.实现功能
3.1.查找存储某一元素节点的前后节点
这里需要将考虑查找节点的位置,分为头节点、中间节点、尾节点
//1.查找平民的前一个与后一个
temp=first;
String name="平民";
if(first.value.equals(name)){
System.out.println("平民为第一个,下一个为"+first.next.value);
} else {
while(temp.next.value!=name){
temp=temp.next;
}
if(temp.next.next==null){
System.out.println("平民为最后一个,上一个为"+temp.value);
}else{
System.out.println("平民前一个是:"+temp.value);
System.out.println("平民后一个是:"+temp.next.next.value);
}
}
头节点输出
中间节点输出
尾节点输出
3.2. 删除节点
*删除中间节点
把删除节点的前节点指向删除节点指向的节点
//2.删除第三个
temp=first;
for(int i=0;i<1;i++){
temp=temp.next;
}
temp.next=temp.next.next;
temp=first;
while(temp.next!=null){
System.out.print(temp.value+",");
temp=temp.next;
}
System.out.println(temp.value);
*删除头节点
将头节点first改为头节点指向的下一个节点
//3.删除第一个
first=first.next;
*删除尾节点
将指向尾节点的节点指向null
temp=first;
while(temp.next.next!=null){
temp=temp.next;
}
temp.next=null;
3.3.插入节点
temp=first;
Node pro=first;遍历时存储前一节点
int x=7;//插入节点所在位置1,2,3,4…………
Object v="法官";//节点存储内容
Node addnode=new Node(v,null);
//若存入头部
if(x==1){
addnode.next=first;
first=addnode;
}else{
for(int i=0;(i<x-1);i++){
pro=temp;
temp=temp.next;
//遍历到尾节点或链表长度不够
if(temp==null){
System.out.println("将节点存入链表尾部");
break;
}
}
pro.next=addnode;
addnode.next=temp;
}
x=1
x=3
x=100
3.4.交换节点位置
在掌握了删除和插入节点的操作后,我们可以结合两者实现交换节点位置的功能
先记录所交换两个节点的位置,再删除这两个节点,最后添加节点
temp=first;
String str1="狼人";
String str2="猎人";
int n1=0,n2=0;
for(int j=1;temp!=null;j++){
if(temp.value.equals(str1)){
n1=j;
} else if (temp.value.equals(str2)) {
n2=j;
}
temp=temp.next;
}
temp=first;
for(int i=0;i<2;i++){
if(first.value.equals(str1)||first.value.equals(str2)){
first=first.next;
} else {
while(temp.next.value!=str1&&temp.next.value!=str2){
temp=temp.next;
}
if(temp.next.next==null){
temp.next=null;
}else{
temp.next=temp.next.next;
}
}
temp=first;
}
temp=first;
Node pro=first;
String x[]={str1,str2};
int y[]={n2,n1};
for(int t=0;t<2;t++){
Node addnode=new Node(x[t],null);
if(n1<n2){
y[0]-=1;
}
if(y[t]==1){
addnode.next=first;
first=addnode;
}else{
for(int i=0;i<(y[t]-1);i++){
pro=temp;
temp=temp.next;
}
pro.next=addnode;
addnode.next=temp;
}
temp=first;
}
狼人与猎人交换
医生与射手交换
String str1="医生";
String str2="射手";