3-输入一个链表,输出该链表中倒数第k个结点

题目:输入一个链表,输出该链表中倒数第k个结点

  • 代码如下
 1 public class Demo2 {
 2     public static void main(String[] args) {
 3         // 先创建多个节点,供测试使用
 4         ListNode listNode1 = new ListNode(1);
 5         ListNode listNode2 = new ListNode(2);
 6         ListNode listNode3 = new ListNode(3);
 7         ListNode listNode4 = new ListNode(4);
 8         ListNode listNode5 = new ListNode(5);
 9         // 把各个节点链起来
10         listNode1.next = listNode2;
11         listNode2.next = listNode3;
12         listNode3.next = listNode4;
13         listNode4.next = listNode5;
14         listNode5.next = null;
15         
16         System.out.println("原始链表中的数据如下:");
17         printList(listNode1);
18         
19         int k = 3;
20         ListNode findKthToTail = findKthToTail(listNode1, k);
21         System.out.println("\n\n倒数第"+k+"个节点是:"+findKthToTail.val);
22         
23     }
24 
25     public static ListNode findKthToTail(ListNode head, int k) {
26         // 首先判断k是否超出了链表的长度
27         // 求得链表的长度
28         int listNodeLength = getListNodeLength(head);
29         ListNode tempNode = head;
30         
31         //传入的k值要在 1~listNodeLength 之间
32         if (k > 0 && k <= listNodeLength) {
33             int j = listNodeLength - k;
34             while (j > 0) {
35                 tempNode = tempNode.next;
36                 j--;
37             }
38         }else{
39             return null;
40         }
41         return tempNode;
42     }
43 
44     /**
45      * 求出链表的长度
46      * @param head
47      * @return
48      */
49     public static int getListNodeLength(ListNode head) {
50         ListNode tempNode = head;
51         int length = 0;
52         while (tempNode != null) {
53             tempNode = tempNode.next;
54             length++;
55         }
56         return length;
57     }
58 
59     /**
60      * 遍历单链表
61      * @param listNode
62      */
63     public static void printList(ListNode listNode) {
64         ListNode tempNode = listNode;
65         while(tempNode != null){
66             System.out.printf("%d\t",tempNode.val);
67             tempNode = tempNode.next;
68         }
69     }
70 }
1 public class ListNode {
2     int val;
3     ListNode next = null;
4 
5     public ListNode(int val) {
6         this.val = val;
7     }
8 }
  • 运行截图

    

猜你喜欢

转载自www.cnblogs.com/sun-/p/12680678.html