1.問題描述
輸入一個鏈表,輸出該鏈表中倒數第k個節點。爲了符合大多數人的習慣,本題從1開始計數,即鏈表的尾節點是倒數第1個節點。例如,一個鏈表有6個節點,從頭節點開始,它們的值依次是1、2、3、4、5、6。這個鏈表的倒數第3個節點是值爲4的節點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 k = 2.
返回鏈表 4->5.
2.問題分析
本題就是鏈表的簡單應用,我們可以用兩個指針來確定我們倒數第K個結點得到位置即可,具體看代碼就行
3.代碼實現
3.1C++代碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode* cur = head;
for(int i = 0; i < k; i ++) cur = cur->next;
while(cur) {
cur = cur->next; //輔助指針當它指向NULL的時候就找到了倒數第K個結點
head = head->next; //找到倒數第K個結點的位置
}
return head;
}
};
3.2Java代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode cur=head;
for(int i=0;i<k;i++)
cur=cur.next;
while(cur!=null)
{
cur=cur.next;
head=head.next;
}
return head;
}
}