编写函数以在C ++中获取链表中的第N个节点
在这里,我们得到一个链表和一个索引。我们必须编写一个函数以获取链表中的第N个节点。
让我们举个例子来了解这个问题,
输入项
linked list = 34 -> 4 -> 9 -> 1 , n = 2
输出结果
9
转到由n指定的节点。我们将逐个链接列表中的节点,并增加索引计数,直到达到所需的第n个位置。
程序说明程序,
示例
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int findNodeAt(Node* head, int index) {
Node* current = head;
int count = 0;
while (current != NULL){
if (count == index)
return(current->data);
count++;
current = current->next;
}
}
int main(){
Node* head = NULL;
insertNode(&head, 8);
insertNode(&head, 2);
insertNode(&head, 9);
insertNode(&head, 1);
insertNode(&head, 4);
int n = 2;
cout<<"Element at index "<<n<<" is "<<findNodeAt(head, 2);
return 0;
}输出结果
Element at index 2 is 9
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便