返回链表的倒数第K个数

public ListNode FindKthToTail(ListNode head, int k) {
//如果链表为空,输入的倒数数少于0,k大于总的长度
if (head == null || k <= 0||k>=5) {
return null;
}
//创建两个链表指针,一个初始化为head,一个为空
ListNode ANode = head;
ListNode BNode = null;
//当走了K-1步之后。B开始走
for (int i = 0; i < k - 1; i++) {
if (ANode.next != null)
ANode = ANode.next;
else
return null;
}
//B走完了返回B的值
BNode = head;
while (ANode.next != null) {
ANode = ANode.next;
BNode = BNode.next;
}
return BNode;
}


public static void main(String[] args) {
ListNode head = new ListNode();
ListNode second = new ListNode();
ListNode third = new ListNode();
ListNode forth = new ListNode();
//head的下一个指针是second
head.next = second;
second.next = third;
third.next = forth;
head.data = 1;
second.data = 2;
third.data = 3;
forth.data = 4;
Project test = new Project();
ListNode result = test.FindKthToTail(head, 3);
System.out.println(result.data);
}

}

public class ListNode {
 
ListNode next = null;
    int data;


ListNode() {


}
}

猜你喜欢

转载自blog.csdn.net/qq_21406125/article/details/80239863