題目1517:鏈表中倒數第k個結點

#include <cstdio>
#include <cstdlib>
using namespace std;
struct Node 
{
   int num;
   Node * next;       
};
 
int getK(Node * head,int k,int nn)
{
   Node * fast,* slow ;
   int i;
   if(head->next==NULL||k==0||k>nn)
       return -1;
   fast=head->next;
   slow=head->next;
   for(i=1;i<k;i++)
   {
       fast=fast->next;                
   }   
   while(fast->next!=NULL)
   {
       fast=fast->next;
       slow=slow->next;                 
   }
   return slow->num;
}
 
int main()
{
   int n,k,num,result;
   Node * head=NULL;
   Node * p=head;
   Node * temp=NULL;
   while(~scanf("%d %d",&n,&k)) 
   {
       int nn=n;
       head=(Node *)malloc(sizeof(Node ));  //head當作頭結點 
       head->next=NULL;
       p=head;
       while(n--)
       {  
          scanf("%d",&num);
          temp= (Node *)malloc(sizeof(Node ));  
          temp->num=num;
          temp->next=NULL;
          p->next=temp;
          p=p->next;    
       }
       result=getK(head,k,nn);
       if(result==-1) 
          printf("NULL\n");
       else
          printf("%d\n",result);
   }    
   return 0;
}
 
/**************************************************************
    Problem: 1517
    User: 蕭然677
    Language: C++
    Result: Accepted
    Time:100 ms
    Memory:2604 kb
****************************************************************/

開始時在result=getK(head,k,nn);把n給傳過去了,此時的n在上面的循環中已經減爲0了,故函數getK一直返回-1。。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章