本文共 3558 字,大约阅读时间需要 11 分钟。
查找单链表倒数第k个节点
在编程过程中,我们常常需要处理单链表数据结构的问题。其中一个常见的任务是查找链表中的倒数第k个节点。这个问题看起来简单,但需要仔细思考如何高效地实现,尤其是在链表较长的情况下。
单链表的结构是每个节点仅包含一个指向下一个节点的指针。因此,从头节点到末尾需要依次访问每个节点。查找倒数第k个节点的关键在于确定链表的长度,并根据k的位置来计算所需节点的位置。
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; } }} getK方法查找倒数第1个节点时,返回节点3。getK方法查找倒数第2个节点时,返回节点2。getK方法查找倒数第2个节点时,返回节点2。getK方法查找倒数第5个节点时,返回null,因为链表长度为4,k超出范围。通过这种方法,我们可以高效地查找单链表中的倒数第k个节点。
转载地址:http://xqqoz.baihongyu.com/