編寫一個 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