//求链表中的倒数第K个结点 2014/1/22
//测试用例
//1 - 2 -3 -4 -5 -6
//倒数第 2个 5 倒数 第7个 报错
//空链表 -> error
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *pNext;
}listNode;
listNode * findKthToTail(listNode *pListHead,unsigned int k)
{
if(pListHead == NULL || k==0)
{
return NULL;
}
listNode *pAhead=pListHead,*pBehind=pListHead;
for(unsigned int i=1;i<=k-1;++i)
{
pAhead=pAhead->pNext;
if(pAhead==NULL) return NULL;
}
while(pAhead->pNext!=NULL)
{
pAhead=pAhead->pNext;
pBehind=pBehind->pNext;
}
return pBehind;
}
int main(int argc,char *argv[])
{
listNode n1,n2,n3,n4,n5,n6;
listNode *r1,*r2,*r3,*r4;
n1.data=1;
n2.data=2;
n3.data=3;
n4.data=4;
n5.data=5;
n6.data=6;
n1.pNext=&n2;
n2.pNext=&n3;
n3.pNext=&n4;
n4.pNext=&n5;
n5.pNext=&n6;
n6.pNext=NULL;
r1=findKthToTail(&n1,2);
r2=findKthToTail(&n1,7);
r3=findKthToTail(&n1,0);
r4=findKthToTail(NULL,4);
return 0;
}
求链表中的倒数第K个结点
最新推荐文章于 2020-05-29 11:03:00 发布