リンクリストの代替ノードをC言語で印刷する(反復法)
この問題では、プログラムは、反復法を使用して、指定されたリンクリストから代替を印刷する必要があります。
反復法は、条件が値1またはtrueになるまで実行されるループを一般的に使用する方法です。
たとえば、リストにはノード29、34、43、56、88が含まれ、出力には29、43、88などの代替ノードが含まれます。
例
Input: 29->34->43->56->88 Output: 29 43 88
アプローチは、最後のノードまでリスト全体をトラバースすることです。一方、1にインクリメントされるカウンター変数をトラバースすることができ、ユーザーの選択に応じてカウンターが偶数または奇数のときに値が出力されます。ユーザーが0から表示したい場合は、偶数の値のカウンターが表示されます。それ以外の場合は、奇数の値のカウンターが表示されます。
以下のコードは、与えられたアルゴリズムのc実装を示しています。
アルゴリズム
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> Declare Function void alternate(struct node* head) Set int count = 0 Loop While (head != NULL) IF count % 2 = 0 Print head->data Set count++ Set head = head->next End Step 3 -> Declare Function void push(struct node** header, int newdata) Create newnode using malloc function Set newnode->data = newdata Set newnode->next = (*header) set (*header) = newnode step 4 -> In Main() create head pointing to first node using struct node* head = NULL Call alternate(head) STOP>
例
#include <stdio.h>
#include <stdlib.h>
//creating structure of a node
struct node {
int data;
struct node* next;
};
//function to find and print alternate node
void alternate(struct node* head) {
int count = 0;
while (head != NULL) {
if (count % 2 == 0)
printf(" %d ", head->data);
count++;
head = head->next;
}
}
//pushing element into the list
void push(struct node** header, int newdata) {
struct node* newnode =
(struct node*)malloc(sizeof(struct node));
newnode->data = newdata;
newnode->next = (*header);
(*header) = newnode;
}
int main() {
printf("alternate nodes are :");
struct node* head = NULL;
push(&head, 1); //calling push function to push elements in list
push(&head, 9);
push(&head, 10);
push(&head, 21);
push(&head, 80);
alternate(head);
return 0;
} 出力
上記のプログラムを実行すると、次の出力が生成されます。
alternate nodes are : 80 10 1
-
C++のリンクリストの代替ノードの合計
この問題では、リンクリストが表示されます。私たちのタスクは、リンクリストの代替ノードの合計を出力することです。 リンクリストは、リンクを介して相互に接続された一連のデータ構造です。 では、問題に戻りましょう。ここでは、リンクリストの代替ノードを追加します。これは、ノードが位置0、2、4、6、…であることを追加することを意味します 問題を理解するために例を見てみましょう。 入力 4 → 12 → 10 → 76 → 9 → 26 → 1 出力 24 説明 considering alternate strings
-
C ++で再帰を使用して、リンクリストの代替ノードを出力します
リンクリストは、要素を連続していないメモリ位置に格納する線形データ構造です。すべての要素には、リンクリストの次の要素へのポインタが含まれています。 例 − この問題では、リンクリストが与えられ、このリンクリストの要素を印刷する必要がありますが、代替要素のみが印刷されます。問題をよりよく理解するために例を見てみましょう。 Input : 2 -> 4 -> 1 -> 67 -> 48 -> 90 Output : 2 -> 1 -> 48 説明 −リンクリストに代替要素を出力します。したがって、1番目、3番目、5番目の要素が印刷されます。