链表-单链表中的倒数第k个节点-3
尚硅谷-链表
https://www.cnblogs.com/zh-xiaoyuan/p/15059026.html
第一种方式:
下面的方式相当于是遍历了2次 ,时间复杂度上太高
//查找单链表中的倒数第k个结点 【新浪面试题】 //1. 编写一个方法,接收head节点,同时接收一个index //2. index 表示是倒数第index个节点 //3. 先把链表从头到尾遍历,得到链表的总的长度 getLength //4. 得到size 后,我们从链表的第一个开始遍历 (size-index)个,就可以得到 //5. 如果找到了,则返回该节点,否则返回nulll public static HeroNode findLastIndexNode(HeroNode head, int index) { //判断如果链表为空,返回null if (head.next == null) { return null;//没有找到 } //第一此遍历得到链表的长度(节点个数) int size = getLength(head); //第二次遍历 size-index位置就是我们倒数的第K个节点 //先做一个index的校验 if (index <= 0 || index > size) { return null; } //定义辅助变量,for循环定位到倒数的index HeroNode cur = head.next; for (int i = 0; i < size - index; i++) { cur = cur.next; } return cur; } //获取单链表节点的个数 public static int getLength(HeroNode head) { if (head.next == null) { //空链表 return 0; } int length = 0; //定义一个辅助的变量, 这里我们没有统计头节点 HeroNode cur = head.next; while (cur != null) { length++; cur = cur.next;//遍历 } return length; }
第二种方式:
https://blog.csdn.net/bruce_xia6116/article/details/100137419
双指针法:定义两个指针,一个快,一个慢;快的指针比慢的指针快k个结点;然后两个指针同时开始遍历,当快的指针指向尾结点时,慢的指针将指向倒数第k个结点。但是在此过程中需要注意判断输入的k是否合法(不能为0;不能超过链表的长度)
public class Code015 { public static void main(String[] args){ ListNode node1=new ListNode(1); ListNode node2=new ListNode(2); ListNode node3=new ListNode(3); ListNode node4=new ListNode(4); ListNode node5=new ListNode(5); ListNode node6=new ListNode(6); node1.next=node2; node2.next=node3; node3.next=node4; node4.next=node5; node5.next=node6; ListNode pListHead=node1; Scanner sc=new Scanner(System.in); int k=sc.nextInt(); ListNode resultNode=FindKthToTail(pListHead,k); System.out.println(resultNode.value); } private static ListNode FindKthToTail(ListNode pListHead, int k) { //判断k是否合法,以及单链表是否为空 if(pListHead==null || k<=0){ return null; } ListNode pFast=pListHead; ListNode pSlow=null; //因为是从1开始计数;因此快指针应该是比慢指针快k-1个结点 for(int i=0;i<k-1;i++){ if(pFast.next!=null){ pFast=pFast.next; }else {//如果k超过链表长度,那么将返回null return null; } } //定义慢指针初始指向头结点 pSlow=pListHead; //开始遍历,遍历结束条件为快指针指向链表的尾(即快指针的下一个结点指向null) while (pFast.next!=null){ pFast=pFast.next; pSlow=pSlow.next; } return pSlow; } private static class ListNode{ int value; ListNode next; public ListNode() { } public ListNode(int value) { this.value = value; } } }