查找链表中第k个节点
查找链表中第k个节点,也是经常碰到的笔试题。
public class TestLinkedNode3 { public static void main(String[] args) { LinkedNode node1 = new LinkedNode(1); LinkedNode node2 = new LinkedNode(2); LinkedNode node3 = new LinkedNode(3); LinkedNode node4 = new LinkedNode(4); LinkedNode node5 = new LinkedNode(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; System.out.println("链表:"); node1.print(); int k = 3; LinkedNode resNode = findKthToTail(node1, k); System.out.println("查找的第" + k + "个节点为:"); resNode.print(); } /** * 查找链表中第k个节点 */ public static LinkedNode findKthToTail(LinkedNode head, int k) { if (head == null) { return null; } if (k <= 0) { return null; } if (k == 1) { return head; } LinkedNode current = head; //指针指向头节点 int count = 1; //指针指向第几个节点 while (current.next != null) { current = current.next; //指针向前移动 count++; //指针指向第几个节点加一 if (count == k) { break; } } return current; } }
运行结果:
链表:
1->2->3->4->5
查找的第3个节点为:
3->4->5