連結串列中倒數第k個結點 java
阿新 • • 發佈:2018-11-08
連結串列中倒數第k個結點 java
題目描述
輸入一個連結串列,輸出該連結串列中倒數第k個結點。
解析:
最佳程式碼:Java程式碼,通過校驗。程式碼思路如下:兩個指標,先讓第一個指標和第二個指標都指向頭結點,然後再讓第一個指正走(k-1)步,到達第k個節點。然後兩個指標同時往後移動,當第一個結點到達末尾的時候,第二個結點所在位置就是倒數第k個節點了。。
程式碼1:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head, int k) { if(head == null){ return null; } ListNode node = head; int count = 0; while(node != null){ count++; node = node.next; } if(count < k){ return null; } ListNode p = head; for(int i = 0; i < count - k; i++){ p = p.next; } return p; } }
程式碼2:推薦
public class Solution { public ListNode FindKthToTail(ListNode head, int k) { if(head == null || k <= 0){ return null; } ListNode start = head; ListNode end = head; for(int i = 1; i < k; i++){ if(start.next != null){ start = start.next; }else{ return null; } } while(start.next != null){ start = start.next; end = end.next; } return end; } }
程式碼3:
public class Solution { public ListNode FindKthToTail(ListNode head, int k) { if(head == null || k <= 0){ return null; } ListNode start = head; ListNode end = head; for(int i = 1; i < k; i++){ if(start.next != null){ start = start.next; }else{ return null; } } for(int i = k; start.next != null; i++){ start = start.next; end = end.next; } return end; } }