ในปัญหานี้ โปรแกรมต้องพิมพ์รายการสำรองจากลิงค์ลิสต์ที่ให้ไว้ เหลืออีกอันหนึ่งพิมพ์อย่างอื่นและอื่น ๆ โดยใช้วิธีการวนซ้ำ
วิธีการวนซ้ำเป็นวิธีที่โดยทั่วไปใช้การวนซ้ำที่ดำเนินการจนกว่าเงื่อนไขจะมีค่า 1 หรือจริง
สมมติว่ารายการมีโหนด 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