查找单链表的倒数第K个节点,要求只能遍历一次链表
class ListNode{
int data;
ListNode next;
}
public class Link{
public static void FindTailK(ListNode first,int k){
ListNode forward = first;
ListNode backward = first;
while(k-- != 0){
forward = forward.next;
}
while(forward != null){
forward = forward.next;
backward = backward.next;
}
System.out.println(backward.data);
}
public static void main(String[] args) {
ListNode n1 = new ListNode();
ListNode n2 = new ListNode();
ListNode n3 = new ListNode();
ListNode n4 = new ListNode();
ListNode n5 = new ListNode();
n1.data = 1;
n2.data = 2;
n3.data = 3;
n4.data = 4;
n5.data = 5;
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
FindTailK(n1,2);
}
}
删除链表的倒数第k个节点
public class Link{
public static ListNode DeleteTailK(ListNode first,int k){
ListNode forward = first;
ListNode backward = first;
while(k-- != 0){
forward = forward.next;
}
while(forward.next != null){ //即最后的backward为k的前一个节点
forward = forward.next;
backward = backward.next;
}
backward.next = backward.next.next;
return first;
}
public static void print(ListNode head){
while(head != null){
System.out.println(head.data);
head = head.next;
}
}