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 }
  • 運行截圖

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM