1.寻找链表的中间结点
public Node middleNode(Node head) {
if(head==null){
return head;
}
Node slow=head;
Node fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
2.寻找链表倒数第k个结点
方法一:快慢指针
public Node FindKthToTail1(Node head,int k){
//输入一个链表,输出该链表中倒数第k个结点。
if(k<=0||head==null){
throw new ArrayIndexOutOfBoundsException("k的值不合法k="+k);
}
Node slow=head;
Node fast=head;
//先让fast走到第k个结点;
for(int i=0;i<k;i++){
if(fast.next!=null) {
fast = fast.next;
}
else
fast=null;
}
while(fast!=null){
slow=slow.next;
fast=fast.next;
}
return slow;
}
方法二:倒数第k就是size-k个结点
public Node FindKthToTail2(Node head,int k){
Node current =head;
int count=0;
while(current!=null){
count++;
current=current.next;
}
if(k<=0||k>count){
throw new ArrayIndexOutOfBoundsException("k的值不合法k="+k);
}
Node tmp=head;
for(int i=0;i<count-k;i++){
if(tmp.next!=null)
tmp=tmp.next;
}
return tmp;
}