連結串列中倒數第k個節點
題目描述
輸入一個連結串列,輸出該連結串列中倒數第k個結點。
下面是我第一次寫的蠢程式碼 複雜度 n+2k
/*
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 head;
}
if (k <1) {
return null;
}
ListNode qian = null;
int len = 1;
while (head.next != null) {
ListNode ing = head.next;
head.next = qian;
qian = head;
head = ing;
len ++;
}
if (len < k) {
return null;
}
head.next = qian;
qian = null;
while (-- k > 0) {
ListNode ing = head.next;
head.next = qian;
qian = head;
head = ing;
}
head.next = qian;
return head;
}
}
這是我參考別人的寫的程式碼 時間複雜度n 誒跟別人比差的很遠 我還是太菜
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (k < 1 || head == null) {
return null;
}
ListNode a = head;
ListNode b = head;
while (--k > 0) {
b = b.next;
if(b == null) return null;
}
while (b.next != null) {
a = a.next;
b = b.next;
}
return a;
}
}