1.链表的反转
public ListNode ReverseList(ListNode head){
if(head==null){
return head;
}
ListNode pNode=head;
ListNode pre=null;
ListNode newHead=null;
for(pNode!=null){
ListNode pNext=pNode.next;
if(pNext==null){
newHead=pNode;
}
pNode.next=pre;
pre=pNode;
pNode=pNext;
}
return newHead;
}
2.一个链表有环,找出环入口
//1.首先定义快慢指针,快的走两步,慢的走一步。第一次相遇后快走的距离入口和慢指针初始位置到入口的距离相等。2(x+m)=x+m+l+m 得到x=l
public ListNode findLoopPort(ListNode head){
ListNode slow=head;
ListNode fast=head;
while (fast!=null&&fast.next!=null){
slow=head.next;
fast=fast.next.next;
if(slow==fast){
break;
}
}
if(fast==null||fast.next==null){
return null;
}
slow=head;
while (slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
2.部分链表反转
/**
* 反转部分链表1->2->3->4->5->null from 2 to 4。反转后变成1-4>3->2->5->null
*/
public static ListNode reversePart(ListNode head,int from,int to){
int len=0;
ListNode node1=head;
ListNode fPre=null;
ListNode tPos=null;
while (node1!=null){
len++;
fPre=len==from-1?node1:fPre;
tPos=len==to+1?node1:tPos;
node1=node1.next;
}
if(from>to||from<1||to>len){
return head;
}
node1=fPre==null?head:fPre.next;
ListNode node2=node1.next;
node1.next=tPos;
ListNode next=null;
while (node2!=tPos){
next=node1.next;
node2.next=node1;
node1.next=node2;
node2=next;
}
if(fPre!=null){
fPre.next=node1;
return head;
}
return node1;
}