题解 | #输出单向链表中倒数第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");
}
全部评论
要求正序构建链表
3 回复 分享
发布于 2023-04-05 11:14 江苏
感谢,这个很容易看懂 第37行 改成if(arrow!=NULL)刚刚好
点赞 回复 分享
发布于 2022-05-31 22:21
少一个head=head->next吧?
点赞 回复 分享
发布于 2022-06-02 17:46
第37行 找到数第k个节点为啥要判断k节点的下个节点是否为空 不是应该判断k本身的位置吗
点赞 回复 分享
发布于 2022-01-20 12:40

相关推荐

点赞 评论 收藏
分享
05-11 20:45
门头沟学院 Java
有担当的灰太狼又在摸...:零帧起手查看图片
点赞 评论 收藏
分享
评论
2
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务