zoukankan      html  css  js  c++  java
  • 链表例题2:链表的倒数第k个节点是多少

    解题思想:

    1.创建一个结点类(为后面实现链表做基础)

    2.创建一个查询倒数元素的方法

    3.使用快慢指针的思想(主要的部分)

    图中的表示的是查询倒数第k个结点的操作:

      创建一个快慢指针后pre(慢指针)指向的第一个结点,在通过k的具体数值来移动p1(快指针),让它们之间包含k个结点(包括它们自身),然后不断的将p1和pre向后移动,直到p1移动到最后一个结点的,此时pre所指的即为倒数第k个的结点。

    代码如下:

     1 public class InquiryNode {
     2 
     3     public static void main(String[] args) {
     4         int arr[]= {1,2,3,4,5,6,7,8};
     5         Node head=new Node(); 
     6         //将数组存储数据用链表串起来
     7         Node p=head;
     8         for(int i=0;i<arr.length;i++)
     9         {
    10             p.next=new Node(arr[i]);
    11             p=p.next;
    12         }
    13         
    14         System.out.println(Inquiry(head,5));
    15         
    16     }
    17     
    18     //查找倒数第K位结点值的方法
    19     public static Object Inquiry(Node node,int k) 
    20     {
    21         if(k<=0)
    22         {
    23             return null;
    24         }
    25         
    26         Node pre=node.next; //慢指针
    27         Node p1=node.next; //快指针
    28         //拉开快慢指针的距离
    29         int count=1;
    30         while(p1!=null&&count<k)
    31         {
    32             p1=p1.next;
    33             count++;
    34         }
    35         //如果k大于元素个数之和则为空
    36         if(p1==null)
    37         {
    38             return null;
    39         }
    40         //将快指针移动到最后一位,同时慢指针也以相同的进度跟上
    41         while(p1.next!=null)
    42         {
    43             pre=pre.next;
    44             p1=p1.next;
    45         }
    46         //慢指针所指的就是倒数第K的元素
    47         return pre.data;
    48     }
    49     
    50 }
    51 
    52     //结点类
    53     class Node{
    54         Object data;
    55         Node next;
    56         
    57         public Node()
    58         {
    59             
    60         }
    61         public Node(int data)
    62         {
    63             this.data=data;
    64         }
    65      }

    结果:

  • 相关阅读:
    (5)html表单
    (4)html表格
    (3)HTML ”列表“、图片和超链接
    (1)html开头解说与案例演示
    学习web前端前感
    一、资源合并与压缩
    HTTP协议原理
    图解HTTP总结
    基于TypeScript从零重构axios
    元組
  • 原文地址:https://www.cnblogs.com/LgxBoKeYuan/p/10202270.html
Copyright © 2011-2022 走看看