題目描述
輸入一個鏈表,輸出該鏈表中倒數第k個結點。
提交代碼:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if (pListHead==NULL|| k<0) #第一步判斷接收數據是否有誤
{
return NULL;
}
ListNode* pre = pListHead;
ListNode* last = pListHead;
int i = 0;
while (pre!=NULL)
{
if (i<k) #找低k個數
{
pre = pre->next;
i++;
}
else #一起向後移動
{
pre = pre->next;
last = last->next;
}
}
if (i<k) #K過大
{
return NULL;
}
return last;
}
};
測試代碼:
int main()
{
Solution *s = new Solution();
//vector<int> v = { 2,4,6,1,3,5,7 };
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(2);
ListNode *l3 = new ListNode(3);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
ListNode *l6 = new ListNode(6);
ListNode *l7 = new ListNode(7);
l1->next = l2;
l2->next = l3; l3->next = l4; l4->next = l5;
l5->next = l6; l6->next = l7;
ListNode* out_list =s->FindKthToTail(l1,3);
system("pause");
return 0;
}
結果: