在 C++ 中查詢連結串列中的模節點
在這個問題中,我們給定一個單鏈表 LL 和一個數字 k。我們的任務是查詢連結串列中的模節點。
問題描述 − 我們需要找到連結串列的最後一個節點,該節點的索引是 k 的倍數,即 i % k == 0。
我們舉個例子來理解這個問題,
輸入
ll = 3 -> 1 -> 9 -> 6 -> 8 -> 2, k = 4
輸出
6
解釋
The element 6 has index 4, which is divisible by 4.
解決方案方法
這個問題的一個簡單解決方案是建立一個計數器來統計連結串列中的元素,並存儲模節點,即 i % k == 0 的節點,並更新所有滿足條件的值直到 n。
程式來說明我們解決方案的工作原理,
示例
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* newNode(int data) {
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
Node* findModularNodeLL(Node* head, int k) {
if (k <= 0 || head == NULL)
return NULL;
int i = 1;
Node* modNode = NULL;
for (Node* currNode = head; currNode != NULL; currNode =
currNode->next) {
if (i % k == 0)
modNode = currNode;
i++;
}
return modNode;
}
int main() {
Node* head = newNode(3);
head->next = newNode(1);
head->next->next = newNode(9);
head->next->next->next = newNode(6);
head->next->next->next->next = newNode(8);
head->next->next->next->next->next = newNode(2);
int k = 4;
Node* modularNode = findModularNodeLL(head, k);
cout<<"The Modular node of linked list is ";
if (modularNode != NULL)
cout<<modularNode->data;
else
cout<<"Not found!";
return 0;
}輸出
The Modular node of linked list is 6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP