fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // การกำหนดโครงสร้างของโหนด
  5. typedef struct Node {
  6. int data;
  7. struct Node* next;
  8. } Node;
  9.  
  10. // ฟังก์ชันสำหรับสร้างโหนดใหม่
  11. Node* createNode(int data) {
  12. Node* newNode = (Node*)malloc(sizeof(Node));
  13. newNode->data = data;
  14. newNode->next = NULL;
  15. return newNode;
  16. }
  17.  
  18. // ฟังก์ชันเพิ่มโหนดที่หัวของรายการ
  19. void insertAtHead(Node** head, int data) {
  20. Node* newNode = createNode(data);
  21. newNode->next = *head;
  22. *head = newNode;
  23. }
  24.  
  25. // ฟังก์ชันลบโหนด
  26. void deleteNode(Node** head, int key) {
  27. Node *temp = *head, *prev;
  28. if (temp != NULL && temp->data == key) {
  29. *head = temp->next;
  30. free(temp);
  31. return;
  32. }
  33. while (temp != NULL && temp->data != key) {
  34. prev = temp;
  35. temp = temp->next;
  36. }
  37. if (temp == NULL) return;
  38. prev->next = temp->next;
  39. free(temp);
  40. }
  41.  
  42. // ฟังก์ชันค้นหาโหนด
  43. Node* searchNode(Node* head, int key) {
  44. Node* current = head;
  45. while (current != NULL) {
  46. if (current->data == key) return current;
  47. current = current->next;
  48. }
  49. return NULL;
  50. }
  51.  
  52. // ฟังก์ชันแสดงรายการที่เชื่อมโยง
  53. void printList(Node* node) {
  54. while (node != NULL) {
  55. printf("%d -> ", node->data);
  56. node = node->next;
  57. }
  58. printf("NULL\n");
  59. }
  60.  
  61. // ฟังก์ชันหลัก
  62. int main() {
  63. Node* head = NULL;
  64. insertAtHead(&head, 1);
  65. insertAtHead(&head, 2);
  66. insertAtHead(&head, 3);
  67. printList(head);
  68. deleteNode(&head, 2);
  69. printList(head);
  70. Node* found = searchNode(head, 3);
  71. if (found != NULL) {
  72. printf("Found node with data %d\n", found->data);
  73. } else {
  74. printf("Node not found\n");
  75. }
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
3 -> 2 -> 1 -> NULL
3 -> 1 -> NULL
Found node with data 3