1. 題目描述
輸入一個鏈表,輸出該鏈表中倒數第k個結點。
2. 解體思路
方法一:簡單來說就是先遍歷整個鏈表的長度L,然後根據k,從頭節點開始遍歷,到L-k,得到相應的節點。
方法二:兩個指針,先讓第一個指針和第二個指針都指向頭結點,然後再讓第一個指針走(k-1)步,到達第k個節點。然後兩個指針同時往後移動,當第一個結點到達末尾的時候,第二個結點所在位置就是倒數第k個節點了。
3. 代碼實現
方法一:
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public class FindKthToTail {
public static void main(String[] args) {
// 定義節點
ListNode root = new ListNode(0) ;
ListNode n1 = new ListNode(3) ;
ListNode n2 = new ListNode(5) ;
ListNode n3 = new ListNode(6) ;
ListNode n4 = new ListNode(7) ;
ListNode n5 = new ListNode(9) ;
// 連接節點
root.next=n1;
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
ListNode tmpnode=FindToTail(root, 5);
System.out.println(tmpnode.val);
}
public static ListNode FindToTail(ListNode head, int k) {
if(head==null || k<=0) {
return null;
}
ListNode node=head;
int count=0;
while(node!=null) {
node=node.next;
count++;
}
System.out.println(count);
if (count < k)
return null;
ListNode nodetmp=head;
for(int i=0; i<count-k; i++) {
nodetmp=nodetmp.next;
}
return nodetmp;
}
}
方法二:
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public class FindKthToTail {
public static void main(String[] args) {
// 定義節點
ListNode root = new ListNode(0) ;
ListNode n1 = new ListNode(3) ;
ListNode n2 = new ListNode(5) ;
ListNode n3 = new ListNode(6) ;
ListNode n4 = new ListNode(7) ;
ListNode n5 = new ListNode(9) ;
// 連接節點
root.next=n1;
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
ListNode tmpnode=FindToTail(root, 2);
System.out.println(tmpnode.val);
}
public static ListNode FindToTail(ListNode head, int k) {
if(head==null || k<=0) {
return null;
}
ListNode pre=head;
ListNode last=head;
for(int i=1; i<k; i++) {
if(pre.next!=null) {
pre=pre.next;
}else {
return null;
}
}
while(pre.next!=null) {
pre=pre.next;
last=last.next;
}
return last;
}
}
運行:
7