package java程序员面试笔试宝典;
public class 题8_1_3找出单链表中倒数第k个元素 {
public static void main(String[] args) {
题8_1链表基本操作 list=new 题8_1链表基本操作();
list.addNode(5);
list.addNode(5);
list.addNode(5);
list.addNode(1);
list.addNode(2);
list.addNode(5);
list.addNode(8);
list.addNode(1);
list.addNode(5);
list.addNode(8);
list.addNode(5);
list.addNode(1);
list.printList();
System.out.println();
System.out.println(findElem(list.head, 12).data);
}
//length
public static int length(Node head){
int count=1;
Node p=head;
if(p==null){
return 0;
}
while(p.next!=null){
count++;
p=p.next;
}
return count;
}
public static Node findElem(Node head,int k){
if(k<1||k>length(head)){
return null;
}
Node p=head;
Node q=head;
for (int i = 0; i < k-1; i++) {
q=q.next;
}
while(q.next!=null){
q=q.next;
p=p.next;
}
return p;
}
}
public class 题8_1_3找出单链表中倒数第k个元素 {
public static void main(String[] args) {
题8_1链表基本操作 list=new 题8_1链表基本操作();
list.addNode(5);
list.addNode(5);
list.addNode(5);
list.addNode(1);
list.addNode(2);
list.addNode(5);
list.addNode(8);
list.addNode(1);
list.addNode(5);
list.addNode(8);
list.addNode(5);
list.addNode(1);
list.printList();
System.out.println();
System.out.println(findElem(list.head, 12).data);
}
//length
public static int length(Node head){
int count=1;
Node p=head;
if(p==null){
return 0;
}
while(p.next!=null){
count++;
p=p.next;
}
return count;
}
public static Node findElem(Node head,int k){
if(k<1||k>length(head)){
return null;
}
Node p=head;
Node q=head;
for (int i = 0; i < k-1; i++) {
q=q.next;
}
while(q.next!=null){
q=q.next;
p=p.next;
}
return p;
}
}