题目1517:链表中倒数第k个结点
时间限制:1 秒
内存限制:128 兆
特殊判题:否
提交:1931
解决:867
-
题目描述:
-
输入一个链表,输出该链表中倒数第k个结点。
(hint: 请务必使用链表。)
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为两个整数n和k(0<=n<=1000, 0<=k<=1000):n代表将要输入的链表元素的个数,k代表要查询倒数第几个的元素。
输入的第二行包括n个数t(1<=t<=1000000):代表链表中的元素。
-
输出:
-
对应每个测试案例,
若有结果,输出相应的查找结果。否则,输出NULL。
-
样例输入:
-
5 2 1 2 3 4 5 1 0 5
-
样例输出:
-
4 NULL
-
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; }Node; int main() { int n,num; int i; while(scanf("%d",&n)!=EOF)//Ctrl+z结束 { scanf("%d",&num); Node *head=(Node *)malloc(sizeof(Node)); Node *p,*q; p=head; int count=0; for(i=0;i<n;++i) { int x; scanf("%d",&x); q=(Node *)malloc(sizeof(Node)); q->data=x; p->next=q; p=q; } head=head->next; p->next=NULL; if(num<=0||num>n) printf("NULL\n"); else { Node *find=head; while(find->next!=NULL)//误写find->data!=NULL,编写代码的过程要特别小心 { if(count==n-num) { printf("%d\n",find->data); break; } else { find=find->next; count++; } } /*Node *find = head; for (int i=0; i<num-1; i++) { find = find->next; } while (find->next!=NULL) { find = find->next; head = head->next; } printf("%d\n",head->data); */ } } return 0; } /************************************************************** Problem: 1517 User: road Language: C Result: Accepted Time:100 ms Memory:2496 kb ****************************************************************/
-
1.C/C++结构体的使用
-
本题的编译环境为C,
-
<pre name="code" class="cpp">struct node { int data; struct node *next; }; node *p;
-
上述形式的定义C++没有问题,类似于class;但用于C编译过不了,提示如下的错误:
-
原因在于:C中结构体变量的声明必须带有关键字struct,即struct node *p; 为避免麻烦,课使用关键字typedef简化,将上述代码改写为:Main.c:6: error: expected specifier-qualifier-list before ‘node’ Main.c: In function ‘main’: Main.c:16: error: ‘node’ undeclared (first use in this function) Main.c:16: error: (Each undeclared identifier is reported only once Main.c:16: error: for each function it appears in.) Main.c:16: error: ‘head’ undeclared (first use in this function) Main.c:16: error: expected expression before ‘)’ token
-
typedef struct node { int data; struct node *next; }Node; Node *p;
-
2.输出链表倒数第k个元素
-
(1)从第一个结点开始遍历,直到第n-k个结点,输出结点的值;
-
(2)因此采取判断链表循环的思路,采用两个指针,第一个指针提前k-1步向下走,第二个指针再随着第一个指针一直走,直到第一个指针指向末尾,此时第二个指针的元素的值,便是我们所要求得的值。