1.题目描述:
求链表中的倒数第k个结点
2.考虑情况:
1)输入的指针为空;
2)结点总数小于k;
3)输入的k为0。
3.拓展情况:
1)求链表的中间结点;
2)判断一个单向链表是否构成了环形结构。(尝试定义两个指针遍历链表,一个指针遍历的速度要比另外一个指针要快,也就是一个一次走一步,另一个一次走两步或者多步)
4.源代码:
// Copyright (c) 2015年 skewrain. All rights reserved.
using namespace std;
#include <iostream>
#include <stdio.h>
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
ListNode *CreateLink(int a[],int k)
{
ListNode *Head = NULL,*q=NULL;
for (int i=0; i<k; i++) {
ListNode *pNew = new ListNode();
pNew->m_nValue = a[i];
pNew->m_pNext = NULL;
if (Head == NULL) {
Head = pNew;
q=pNew;
}
else
{
q->m_pNext=pNew;
q=q->m_pNext;
}
}
return Head;
}
//从头到尾打印链表
void printLink(ListNode *pHead)
{
cout<<"链表内容为:";
ListNode *p = pHead;
while (p) {
cout<<p->m_nValue<<"";
p=p->m_pNext;
}
cout<<endl;
}
//求链表中的倒数第k个结点
ListNode *FindKthToTail(ListNode *pListHead,unsigned int k){
if(pListHead == NULL || k ==0)
return NULL;
ListNode *pAhead = pListHead;
ListNode *pBehind = NULL;
for(unsigned int i=0;i<k-1;++i)
{
if(pAhead->m_pNext!=NULL)
pAhead = pAhead->m_pNext;
else
{
return NULL;
}
}
pBehind = pListHead;
while (pAhead->m_pNext!=NULL) {
pAhead = pAhead->m_pNext;
pBehind = pBehind->m_pNext;
}
return pBehind;
}
//========测试用例========
//1.pListHead为空
void Test1()
{
cout<<"测试用例1"<<endl;
ListNode *ptr = NULL;
printLink(ptr);
ListNode *p=FindKthToTail(NULL, 0);
if(p)
cout<<p->m_nValue<<endl;
}
//2.长度为n,k>n时
void Test2()
{
cout<<"测试用例2"<<endl;
int a[]={1,2,3,4,5};
ListNode *ptr = CreateLink(a,5);
printLink(ptr);
ListNode *p = FindKthToTail(ptr, 6);
if(p)
cout<<p->m_nValue<<endl;
}
//3.k==0
void Test3()
{
cout<<"测试用例3"<<endl;
int a[]={1,2,3,4,5};
ListNode *ptr = CreateLink(a,5);
printLink(ptr);
ListNode *p = FindKthToTail(ptr, 6);
if(p)
cout<<p->m_nValue<<endl;
}
//4.k==1
void Test4()
{
cout<<"测试用例4"<<endl;
int a[]= {1,2,3,4,5};
ListNode *ptr = CreateLink(a,5);
printLink(ptr);
ListNode *p = FindKthToTail(ptr, 1);
if(p)
cout<<p->m_nValue<<endl;
}
//5.k==1,n==1
void Test5()
{
cout<<"测试用例5"<<endl;
int a[]={1};
ListNode *ptr = CreateLink(a, 1);
printLink(ptr);
ListNode *p = FindKthToTail(ptr, 1);
if(p)
cout<<p->m_nValue<<endl;
}
//6.normal
void Test6()
{
cout<<"测试用例6"<<endl;
int a[]={1,2,3,4,5};
ListNode *ptr = CreateLink(a, 5);
printLink(ptr);
ListNode *p = FindKthToTail(ptr, 4);
if (p)
cout<<p->m_nValue<<endl;
}
int main(int argc, const char * argv[]) {
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
/*
//手动创建链表
int n,k;
while (scanf("%d %d",&n,&k) != EOF) {
int i,data;
scanf("%d",&data);
ListNode *p = new ListNode();
if (p) {
exit(EXIT_FAILURE);
}
p->m_nValue = data;
p->m_pNext = NULL;
ListNode *pCur = p;
for (i=0; i<n-1; i++) {
scanf("%d",&data);
ListNode *pNew = new ListNode();
if(pNew == NULL)
exit(EXIT_FAILURE);
pNew->m_nValue = data;
pNew->m_pNext = NULL;
pCur->m_pNext = pNew;
pCur = pCur->m_pNext;
}
ListNode *pFind = FindKthToTail(p, k);
if(pFind == NULL)
printf("NULL");
else
printf("%d\n",pFind->m_nValue);
}
*/
return 0;
}