题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
这题之所以不难应该是因为单链表逆序找值刚刚好用头插法就是逆序的。
我的c语言回答的。一开始碰到一个问题是什么栈超出、后发现是位置超过链表长度的情况没有写(我的if改成while就好了。)
#include<stdio.h>
#include<malloc.h>
typedef struct Node{
int data;
struct Node* next;
}NodeList, * pNodeList;
void fun(int n)
{
int i=0,data=0,targetIndex;
pNodeList head = (pNodeList)malloc(sizeof(NodeList));
head->next = NULL;
for(i=0;i<n;i++)
{
pNodeList new = (pNodeList)malloc(sizeof(NodeList));
scanf("%d",&new->data);
new->next = head->next;
head->next = new;
}
scanf("%d",&targetIndex);
pNodeList arrow = head;
if(targetIndex>n){}
else{
for(i=0;i<targetIndex;i++)
{
arrow= arrow->next;
}
if(arrow->next !=NULL)
{
printf("%d\n",arrow->data);
}
}
}
void main()
{
int n;
while(scanf("%d\n",&n)!=EOF)
fun(n);
system("pause");
}