题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <iostream>
#include<list>
#include<vector>
#include<sstream>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
ListNode * insert_node(ListNode* head,int data)
{
ListNode* new_node=nullptr;
if(head==nullptr)
{
head=new(ListNode);
head->m_nKey=data;
head->m_pNext=nullptr;
return head;
}
new_node=new(ListNode);
new_node->m_nKey=data;
new_node->m_pNext=head;
head=new_node;
return head;
}
int num_node(ListNode* head)
{
int num=0;
while(head!=nullptr)
{
num++;
head=head->m_pNext;
}
return num;
}
void prin(ListNode* head)
{
while(head!=nullptr)
{
cout<<head->m_nKey<<" ";
head=head->m_pNext;
}
}
int main()
{
while(!std::cin.eof())
{
int num=0;
cin>>num;
ListNode* head=nullptr;
int data;
while(num--)
{
cin>>data;
head=insert_node(head,data);
}
// prin(head);
int L_size=num_node(head);
int re_posi=0;
cin>>re_posi;
//head=remove_node(head,re_posi);
int cnt=1;
while(head!=nullptr)
{
if(cnt==re_posi)
{
cout<<head->m_nKey<<endl;
break;
}
head=head->m_pNext;
cnt++;
}
}
// prin(head);
return 0;
}
// 64 位输出请用 printf("%lld")