实现链表的增加、删除、查找和反转
class Link{
public int iData;
public Link next;
public Link(int data){
iData=data;
}
public void display(){
System.out.print(iData+" ");
}
}
class LinkList{
private Link first;
public LinkList(){
first=null;
}
//插入头节点
public void insertFirst(int data){
Link newlink=new Link(data);
newlink.next=first;
first=newlink;
}
//删除头结点
public Link deleteFirst(){
Link temp=first;
first=first.next;
return temp;
}
//查找
public Link find(int key){
Link current=first;
while(current.iData!=key){
if(current.next==null){
return null;
}else{
current=current.next;
}
}
return current;
}
//删除任意节点
public Link delete(int key){
Link current=first;
Link previous=first;
while(current.iData!=key){
if(current.next==null){
return null;
}else{
previous=current;
current=current.next;
}
}
if(current==first){
first=first.next;
}else{
previous.next=current.next;
}
return current;
}
//反转链表-循环
public void reverse(){
Link current=first;
Link nextlink=null;
Link prelink=null;
while(current!=null){
//存储为反转前的next节点
nextlink=current.next;
//反转当前节点的指针为当前节点的前一个节点
current.next=prelink;
//所有指针向后移动
prelink=current;
current=nextlink;
}
}
//反转链表-递归
public Link recReverse(Link current){
current=first;
Link nextlink=null;
if(current==null||current.next==null){
return current;
}
nextlink=current.next;
Link rec=recReverse(nextlink);
nextlink.next=current;
return rec;
}
}
判断链表中是否存在回路,快慢指针法
//判断是否存在回路-快慢指针
public boolean isLoop(){
Link low=first;
Link fast=first;
while((low!=null)&&(fast!=null)){
low=low.next;
fast=fast.next.next;
if(low.iData==fast.iData){
return true;
}
return false;
}