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

更新於: 4 月 20 日, 2020

637 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告