思路:
1.獲取單鏈表的總個數;
2.總個數與K之差即爲從頭結點開始計數的第()個節點;
3.遍歷獲取倒數第k個節點;
代碼實現:
//查找單鏈表中的倒數第k個節點
public int getRecipNode(int k) {
if (HeadNode.next == null) {
throw new RuntimeException("鏈表爲空");
}
Node temp = HeadNode.next;
//獲取鏈表結點的總個數,減去倒數K,就是第()個節點
int num = getNodeNum()-1;
num = num - k;
int count = 0;//計數
int no = 0;
while (true) {
if (count == num) {
no = temp.no;
break;
}
count++;
temp = temp.next;
}
return no;
}
//求單鏈表中結點的個數
public int getNodeNum() {
int num = 0;
Node temp = HeadNode;
while (true) {
if (temp.next == null) {
num++;
break;
}
num++;
temp = temp.next;
}
return num;
}