//用来反转整个链表publicvoidreverse(){//判断当前链表是否为空链表,如果是空链表,则结束运行,如果不是,则调用重载的reverse方法完成反转if(isEmpty()){return;}reverse(head.next);}//反转指定的结点curr,并把反转后的结点返回publicNodereverse(Node curr){if(curr.next==null){
head.next=curr;return curr;}//递归的反转当前结点curr的下一个结点;返回值就是链表反转后,当前结点的上一个结点Node pre =reverse(curr.next);//让返回的结点的下一个结点变为当前结点curr;
pre.next=curr;//把当前结点的下一个结点变为null
curr.next=null;return curr;}
4、快慢指针
4.1 中间值问题
/**
* @param first 链表的首结点
* @return 链表的中间结点的值
*/publicstaticStringgetMid(Node<String> first){Node<String> slow = first;Node<String> fast = first;while(fast!=null&& fast.next!=null){
fast=fast.next.next;
slow=slow.next;}return slow.item;}
4.2 单向链表是否有环问题
/**
* 判断链表中是否有环
* @param first 链表首结点
* @return ture为有环,false为无环
*/publicstaticbooleanisCircle(Node<String> first){Node<String> slow = first;Node<String> fast = first;while(fast!=null&& fast.next!=null){
fast = fast.next.next;
slow = slow.next;if(fast.equals(slow)){returntrue;}}returnfalse;}
4.3 有环链表入口问题
/**
* 查找有环链表中环的入口结点
* @param first 链表首结点
* @return 环的入口结点
*/publicstaticNodegetEntrance(Node<String> first){Node<String> slow = first;Node<String> fast = first;Node<String> temp =null;while(fast!=null&& fast.next!=null){
fast = fast.next.next;
slow=slow.next;if(fast.equals(slow)){
temp = first;continue;}if(temp!=null){
temp=temp.next;if(temp.equals(slow)){return temp;}}}returnnull;}
5、循环链表
//构建结点Node<Integer> first =newNode<Integer>(1,null);Node<Integer> second =newNode<Integer>(2,null);Node<Integer> third =newNode<Integer>(3,null);Node<Integer> fourth =newNode<Integer>(4,null);Node<Integer> fifth =newNode<Integer>(5,null);Node<Integer> six =newNode<Integer>(6,null);Node<Integer> seven =newNode<Integer>(7,null);//构建单链表
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
fifth.next = six;
six.next = seven;//构建循环链表,让最后一个结点指向第一个结点
seven.next = first;
6、约瑟夫问题
publicclassTest{publicstaticvoidmain(String[] args)throwsException{//1.构建循环链表Node<Integer> first =null;//记录前一个结点Node<Integer> pre =null;for(int i =1; i <=41; i++){//第一个元素if(i ==1){
first =newNode(i,null);
pre = first;continue;}Node<Integer> node =newNode<>(i,null);
pre.next = node;
pre = node;if(i ==41){//构建循环链表,让最后一个结点指向第一个结点
pre.next = first;}}//2.使用count,记录当前的报数值int count =0;//3.遍历链表,每循环一次,count++Node<Integer> n = first;Node<Integer> before =null;while(n != n.next){//4.判断count的值,如果是3,则从链表中删除这个结点并打印结点的值,把count重置为0;
count++;if(count ==3){//删除当前结点
before.next = n.next;System.out.print(n.item +",");
count =0;
n = n.next;}else{
before = n;
n = n.next;}}/*打印剩余的最后那个人*/System.out.println(n.item);}}