单链表:求中间结点和倒数第k个结点
//1,找中间点,如果中间结点有两个,第二个为中间结点------长度/2
class ListNode2{
public int data;
public ListNode2 next;
public ListNode2(int data){
this.data=data;
this.next=null;
}
}
class MySingleList2{
public ListNode2 head;
public MySingleList2(){
this.head=null;
}
public ListNode2 middleNode(){
int length=getLength()/2;
ListNode2 cur=this.head;
for (int i = 0; i <length ; i++) {
cur=cur.next;
}
return cur;
}
public int getLength(){
int count=0;
ListNode2 cur=this.head;
while(cur !=null){
count++;
cur=cur.next;
}
return count;
}
public void disPlay(){
ListNode2 cur=this.head;
while (cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
public void addFirst(int data){
ListNode2 node2=new ListNode2(data);
if(this.head==null){
this.head=node2;
}else{
node2.next=head;
this.head=node2;
}
}
}
public class LinkList2 {
public static void main(String[] args) {
MySingleList2 mySingleList2=new MySingleList2();
mySingleList2.addFirst(1);
mySingleList2.addFirst(5);
mySingleList2.addFirst(8);
mySingleList2.addFirst(25);
mySingleList2.addFirst(7);
mySingleList2.addFirst(31);
mySingleList2.addFirst(18);
mySingleList2.addFirst(45);
mySingleList2.disPlay();
ListNode2 node2=mySingleList2.middleNode();
System.out.println(node2.data);
}
}
//10,找倒数第K个结点
class ListNode3{
public int data;
public ListNode3 next;
public ListNode3(int data){
this.data=data;
this.next=null;
}
}
class MySingleList3{
public ListNode3 head;
public MySingleList3(){
this.head=null;
}
public ListNode3 findKthToTail(int k){
if(k<=0 || k>getLenghth()){
return null;
}
ListNode3 fast=this.head;
ListNode3 slow=this.head;
if(fast!=null && slow!=null){
while(k-1>0){
fast=fast.next;
k--;
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
}
return slow;
}
public int getLenghth(){
ListNode3 cur=this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
public void display(){
ListNode3 cur=this.head;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
public void addFirst(int data){
ListNode3 node3=new ListNode3(data);
if(this.head==null){
this.head=node3;
}else{
node3.next=head;
this.head=node3;
}
}
}
public class LinkList3 {
public static void main(String[] args) {
MySingleList3 mySingleList3=new MySingleList3();
mySingleList3.addFirst(10);
mySingleList3.addFirst(7);
mySingleList3.addFirst(8);
mySingleList3.addFirst(46);
mySingleList3.addFirst(89);
mySingleList3.addFirst(67);
mySingleList3.addFirst(45);
mySingleList3.display();
ListNode3 node3=mySingleList3.findKthToTail(3);
System.out.println(node3.data);
}
}