이 문제에서 프로그램은 반복 방법을 사용하여 다른 하나를 인쇄하는 등 주어진 연결 목록에서 대안을 인쇄해야 합니다.
반복 방법은 일반적으로 조건이 값 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