#include<stdio.h>
#include <stdlib.h>
struct Node{
int data;
Node *next;
}node;
Node * printt(Node *p1,int n)
{
Node *pp=p1;
Node *q1=pp->next;
for(int j=1;j<=n;j++)
{
pp=pp->next;
}
while(pp->next!=NULL){
q1=q1->next;
pp=pp->next;
}
return q1;
}
Node* FindKthToTail_Solution2(Node* pListHead, unsigned int k)
{
if(pListHead == NULL)
return NULL;
Node *pAhead = pListHead;
Node *pBehind = pListHead->next;
//printf("succeed1\n");
for(unsigned int i = 0; i < k; ++ i)
{
if(pAhead->next != NULL)
pAhead = pAhead->next;
else {
return NULL;
}
}
//printf("succeed2\n");
while(pAhead->next != NULL) {
pAhead = pAhead->next;
pBehind = pBehind->next;
}
printf("succeed3\n");
return pBehind;
}
int main(){
int a[10]={1,2,3,4,5,6,7,8,9,10};
Node *q=(Node *)malloc(sizeof(Node));
Node *first=q;
for(int k=0;k<10;k++){
Node *p=(Node *)malloc(sizeof(Node));
p->data=a[k];
q->next=p;
q=p;
}
q->next=NULL;
int n=0;
scanf("%d",&n);
Node *qq;
qq=FindKthToTail_Solution2(first,n);
printf("succeed4\n");
printf("倒数第%d个数是%d",n,qq->data);
// while(first->next!=NULL){
// printf("%d ",first->next->data);
// first->next=first->next->next;
// }
return 0;
}
查找链表的倒数第K个结点
最新推荐文章于 2021-12-21 13:38:08 发布