ในบทความนี้ เราได้รับ linked list งานคือสร้างโปรแกรม C เพื่อย้อนกลับค่าของแต่ละโหนดใน singly linked list
เราจะนำแต่ละโหนดของ linked list มาและย้อนกลับค่า
Linked list คือลำดับของลิงก์ที่มีรายการที่เชื่อมโยงกับลิงก์อื่น
ตัวอย่างเพื่อเข้าใจปัญหา
อินพุต
34 12 89 56 72
เอาต์พุต
43 21 98 65 27
เพื่อแก้ปัญหานี้ เราจะวน singly linked list และนำแต่ละโหนด แล้วย้อนกลับค่าของโหนดปัจจุบัน
โปรแกรมย้อนกลับค่าของแต่ละโหนดใน Singly Linked List
// โปรแกรมย้อนกลับค่าของแต่ละโหนดใน Singly Linked List
ตัวอย่างโค้ด
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertNode(int key) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
int reverseValue(int number) {
int revElement = 0, rem;
while (number != 0) {
rem = number % 10;
revElement = revElement * 10 + rem;
number = number / 10;
}
return revElement;
}
void reverseLinkedListElements(struct Node* node) {
if (node == NULL)
return;
while (node != NULL) {
node->data = reverseValue(node->data);
node = node->next;
}
}
void printLinkedList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
head = insertNode(34);
head->next = insertNode(12);
head->next->next = insertNode(89);
head->next->next->next = insertNode(56);
head->next->next->next->next = insertNode(72);
printf("Linked List ต้นฉบับ:\t");
printLinkedList(head);
reverseLinkedListElements(head);
printf("\nLinked List ที่เปลี่ยนแปลง:\t");
printLinkedList(head);
return 0;
}
ผลลัพธ์
Linked List ต้นฉบับ: 34 12 89 56 72 Linked List ที่เปลี่ยนแปลง: 43 21 98 65 27