编写函数以在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