博客
关于我
查找单链表中倒数第k个节点
阅读量:641 次
发布时间:2019-03-14

本文共 3558 字,大约阅读时间需要 11 分钟。

查找单链表倒数第k个节点

在编程过程中,我们常常需要处理单链表数据结构的问题。其中一个常见的任务是查找链表中的倒数第k个节点。这个问题看起来简单,但需要仔细思考如何高效地实现,尤其是在链表较长的情况下。

问题分析

单链表的结构是每个节点仅包含一个指向下一个节点的指针。因此,从头节点到末尾需要依次访问每个节点。查找倒数第k个节点的关键在于确定链表的长度,并根据k的位置来计算所需节点的位置。

解决思路

  • 获取链表长度:首先,我们需要计算链表的总长度。这可以通过遍历链表节点,直到遇到末尾节点(next为null)为止,统计节点数。
  • 判断k的合法性:链表的长度决定了k的合法范围。k必须大于0且小于等于链表长度,否则返回null。
  • 确定目标节点位置:倒数第k个节点的位置可以通过链表长度减去k来确定。例如,链表长度为4,k为1,则目标节点位于位置4-1=3。
  • 遍历到目标节点:从头节点的下一个节点开始,按照计算得到的位置进行遍历,找到目标节点。
  • 代码实现

    package LinkedList.test;public class SingleLinkedListTest {    public static void main(String[] args) {        Node n1 = new Node(1, "123");        Node n2 = new Node(2, "23");        Node n3 = new Node(3, "3");        LinkedList linkedList = new LinkedList();        linkedList.add(n1);        linkedList.add(n2);        linkedList.add(n3);        Node listK = linkedList.getK(linkedList.getHead(), 1);        System.out.println(listK);    }    public static void main2(String[] args) {        Node n1 = new Node(1, "123");        Node n2 = new Node(2, "23");        Node n3 = new Node(3, "3");        Node n4 = new Node(4, "4");        LinkedList linkedList = new LinkedList();        linkedList.add(n1);        linkedList.add(n2);        linkedList.add(n3);        linkedList.add(n4);        Node listK = linkedList.getK(linkedList.getHead(), 2);        System.out.println("倒数第二个节点:" + listK);    }    static class Node {        public int no;        public String data;        public Node next;        Node(int no, String data) {            this.no = no;            this.data = data;        }        @Override        public String toString() {            return "Node{" + "no=" + no + ", data='" + data + '\'' + '}';        }    }    static class LinkedList {        private Node head = new Node(0, "");        public Node getHead() {            return head;        }        public void add(Node node) {            Node temp = head;            while (temp.next != null) {                temp = temp.next;            }            temp.next = node;        }        public void list() {            Node temp = head.next;            if (temp == null) {                System.out.println("该链表为空");                return;            }            while (true) {                System.out.println(temp);                temp = temp.next;                if (temp == null) {                    break;                }            }        }        public int getLength(Node head) {            if (head.next == null) {                return 0;            }            int length = 0;            Node temp = head.next;            while (temp != null) {                length++;                temp = temp.next;            }            return length;        }        public Node getK(Node head, int index) {            if (head.next == null) {                return null;            }            int length = getLength(head);            if (index <= 0 || index > length) {                System.out.println("index数据非法");                return null;            }            Node temp = head.next;            int moveTimes = length - index;            for (int i = 0; i < moveTimes; i++) {                temp = temp.next;            }            return temp;        }    }}

    代码解释

  • Node类:定义了节点的构造方法,包含节点编号和数据字段,以及指向下一个节点的next指针。
  • LinkedList类:管理链表的操作,包括添加节点、遍历链表、获取链表长度和查找倒数第k个节点。
    • getLength方法:通过遍历链表计算长度。
    • getK方法:实现查找倒数第k个节点的逻辑,首先检查链表是否为空和k的合法性,然后计算移动次数并遍历到目标节点。
  • 主函数:创建链表,添加节点,调用查找方法并输出结果。
  • 运行结果示例

    • 当调用getK方法查找倒数第1个节点时,返回节点3。
    • 当调用getK方法查找倒数第2个节点时,返回节点2。
    • 当调用getK方法查找倒数第2个节点时,返回节点2。
    • 当调用getK方法查找倒数第5个节点时,返回null,因为链表长度为4,k超出范围。

    通过这种方法,我们可以高效地查找单链表中的倒数第k个节点。

    转载地址:http://xqqoz.baihongyu.com/

    你可能感兴趣的文章
    Python中*args和**kwargs的使用
    查看>>
    python中0、1、True、False、if条件
    查看>>
    python中argparse模块关于 parse_args() 函数详解(全)
    查看>>
    python中base64编码与解码
    查看>>
    python中break怎么用_详解Python中break语句的用法
    查看>>
    python中del函数的垃圾回收
    查看>>
    Python中DrissionPage的详细解析与实战
    查看>>
    python中enumerate、变量类型转换
    查看>>
    python中execute是啥_python – 为什么“c.execute(…)”打破循环?
    查看>>
    python中exit和break区别_Python中exit()和sys.exit()之间的区别
    查看>>
    python中h5的用法
    查看>>
    python中http协议编程_HTTP编程
    查看>>
    python中if的效率_python中关于if-else使用性能的一点感悟
    查看>>
    python中import os_Python:相对导入与绝对导入(import)、os.path、__file__
    查看>>
    python中is和==操作符
    查看>>
    python中range()函数的返回值是多少?
    查看>>
    Python中range对象的使用以及打印九九乘法表
    查看>>
    Python中reshape函数参数-1的意思?
    查看>>
    Python中set.discard和set.remove方法之间的运行时差异?
    查看>>
    Python接口自动化测试企业级实战
    查看>>