在單次遍歷中查詢 C++ 連結串列的倒數第二個節點


現在我們將學習如何獲取連結串列中的倒數第二個元素。假設有幾個元素,如 [10, 52, 41, 32, 69, 58, 41],倒數第二個元素是 58。

要解決這個問題,我們將使用兩個指標,一個指向當前節點,另一個指向當前位置的前一個節點,然後我們將移動,直到當前節點的下一個節點為空,然後直接返回前一個節點。

示例

 現場演示

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *next;
};
void prepend(Node** start, int new_data) {
   Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = NULL;
   if ((*start) != NULL){
      new_node->next = (*start);
      *start = new_node;
   }
   (*start) = new_node;
}
int secondLastElement(Node *start) {
   Node *curr = start, *prev = NULL;
   while(curr->next != NULL){
      prev = curr;
      curr = curr->next;
   }
   return prev->data;
}
int main() {
   Node* start = NULL;
   prepend(&start, 15);
   prepend(&start, 20);
   prepend(&start, 10);
   prepend(&start, 9);
   prepend(&start, 7);
   prepend(&start, 17);
   cout << "Second last element is: " << secondLastElement(start);
}

輸出

Second last element is: 20

更新於:19-12-2019

580 次瀏覽

開啟你的 事業

完成課程認證

開始
廣告
© . All rights reserved.