问题:
输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针
答案:
//20130112
#include <iostream>
using namespace std;
typedef struct node
{
int n;
node* next;
}node,*pnode;
int main()
{
int a[14]={6,7,8,9,2,3,5,6,7,8,9,0,6,5};
node *pn=new node;
pn->n=a[0];
pn->next=NULL;
pnode p=pn;
for (int i=1;i<14;++i)
{
node *q=new node;
q->n=a[i];
q->next=NULL;
p->next=q;
p=q;
}
int k=3;//倒数第k个节点
pnode pd=pn;
for (int i=0;i<k;++i)
{
pd=pd->next;
}
while(pd->next!=NULL)
{
pn=pn->next;
pd=pd->next;
}
return 0;
}