รายการที่เชื่อมโยงเป็นโครงสร้างข้อมูลเชิงเส้นที่เก็บองค์ประกอบในตำแหน่งหน่วยความจำที่ไม่ต่อเนื่องกัน ทุกองค์ประกอบมีตัวชี้ไปยังองค์ประกอบถัดไปของรายการที่เชื่อมโยง
ตัวอย่าง −

ในปัญหานี้ เราได้รับรายการที่เชื่อมโยงและเราจำเป็นต้องพิมพ์องค์ประกอบของรายการที่เชื่อมโยงนี้ แต่จะพิมพ์เฉพาะองค์ประกอบอื่นเท่านั้น มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากันดีกว่า
Input : 2 -> 4 -> 1 -> 67 -> 48 -> 90 Output : 2 -> 1 -> 48
คำอธิบาย − เราจะพิมพ์องค์ประกอบอื่นในรายการที่เชื่อมโยง ดังนั้นองค์ประกอบที่หนึ่ง สาม และห้าจึงถูกพิมพ์
เราจะใช้องค์ประกอบแฟล็กที่จะเริ่มต้นเป็น 0 และจะเพิ่มขึ้นทุกครั้งที่ทำซ้ำที่พิมพ์องค์ประกอบ มิฉะนั้นจะลดค่าลง และเราจะพิมพ์ค่าโหนดเมื่อแฟล็กเป็น 0
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printAlternateNode(struct Node* head){
int flag = 0;
while (head != NULL) {
if (flag == 0){
printf(" %d ", head->data);
flag = 1;
}
else
flag = 0;
head = head->next;
}
}
void insertNode(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main(){
struct Node* head = NULL;
insertNode(&head, 23);
insertNode(&head, 4);
insertNode(&head, 98);
insertNode(&head, 5);
insertNode(&head, 71);
printAlternateNode(head);
return 0;
} ผลลัพธ์
71 98 23