编写一个 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP