求鏈式線性表的倒數第K項
- 題目
- 答案
- 第一種解法
- 第二種解法(較好)
- 注意
題目

答案
第一種解法
這種方法是正常輸入,然后將鏈表逆置,雖然pta是可以通過的(寫陣列應該都能通過),但明顯沒有下一種好
#include<stdio.h>
#include<malloc.h>
struct Node{
int data;
struct Node *next;
};
int main()
{
struct Node *node,*temp,*p,*head,*older,*news;
int count;
node=(struct Node *) malloc(sizeof(struct Node));
head=node;
int n,t;
scanf("%d",&n);
while(1)
{
scanf("%d",&t);
if(t<0) break;
count++;
temp=(struct Node *) malloc(sizeof(struct Node));
temp->data=t;
temp->next=NULL;
node->next=temp;
node=node->next;
}
if(count<n)
{
printf("NULL");return 0;
}
head=head->next;
news=NULL;
older=head;
while(older)
{
temp=older->next;
older->next=news;
news=older;
older=temp;
}
count=0;
while(1)
{
count++;
if(count==n)
{
printf("%d",news->data);return 0;
}
news=news->next;
}
}
第二種解法(較好)
這種解法就是頭插法,很簡單,我參考了下面這篇文章
https://blog.csdn.net/lovecyr/article/details/90645982
#include<stdio.h>
#include<malloc.h>
struct Node{
int data;
struct Node *next;
};
int main()
{
int k,t,i;
scanf("%d",&k);
struct Node *head,*p;
head=(struct Node *)malloc(sizeof(struct Node));
head->next=NULL;
while(scanf("%d",&t)&&t>=0)
{
p=(struct Node *)malloc(sizeof(struct Node));
p->data=t;
p->next=head->next;
head->next=p;
}
for(i=0;i<k;i++)
head=head->next;
if(head) printf("%d",head->data);
else printf("NULL");
}
注意
記得NULL的情況
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/272909.html
標籤:其他
