//将对应的链表逆置
public ListNode reverse(ListNode head){
ListNode prev=null;
ListNode p=head;
while(p!=null){
//保存对应的结点指针
ListNode temp=p.next;
//连接
p.next=prev;
prev=p;
p=temp;
}
return prev;
}
//通过快慢指针找到中间节点
public ListNode getMidListNode(ListNode head){
//对于快慢指针
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){//
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
如果是要删除中间节点
需要找到中间节点的前一个结点,快慢结点指针同时从虚拟头节点开始出发即可
class Solution {
public ListNode deleteMiddle(ListNode head) {
ListNode dummy=new ListNode(0,head);
ListNode slow=dummy;
ListNode fast=dummy;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
slow.next=slow.next.next;
return dummy.next;
}
}
通过快慢指针判断是否有环
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null){
return false;
}
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null||fast.next==null){
return false;
}
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}
环形链表入环节点
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null){
return null;
}
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null||fast.next==null){
return null;
}
slow=slow.next;
fast=fast.next.next;
}
ListNode ptr=head;
slow=slow.next;//由于初始时候对应的起点已经先走一步了,所以将fast=head时候将slow=slow.next
//如果对应的起点 slow=head;fast=head 对应的直接省略
while(slow!=ptr){
slow=slow.next;
ptr=ptr.next;
}
return ptr;
}
}