คำอธิบาย
Linked List ใช้การจัดสรรหน่วยความจำแบบไดนามิก เป็นชุดของโหนด (Nodes) แต่ละโหนดมี 2 ส่วน: ข้อมูล (Data) และลิงก์ (Link)
ประเภทของ Linked List
- Singly Linked List
- Doubly Linked List
- Circular Singly Linked List
- Circular Doubly Linked List
Doubly Linked List
โหนดมี Pointer 2 ตัว: preptr (ชี้ไปโหนดก่อนหน้า) และ nextptr (ชี้ไปโหนดถัดไป)
โค้ดตัวอย่าง: แทรกโหนดที่ตำแหน่งใดๆ
#include <stdio.h>
#include <stdlib.h>
struct node {
int num;
struct node *preptr;
struct node *nextptr;
} *stnode, *ennode;
void DlListcreation(int n);
void DlLinsertNodeAtBeginning(int num);
void DlLinsertNodeAtEnd(int num);
void DlLinsertNodeAtAny(int num, int pos);
void displayDlList(int a);
int main() {
int n, num1, a, insPlc;
stnode = NULL;
ennode = NULL;
printf("\nDoubly Linked List: Insert node at any position\n");
printf("Input number of nodes: ");
scanf("%d", &n);
DlListcreation(n);
a = 1;
displayDlList(a);
printf("Input position (1 to %d) to insert: ", n+1);
scanf("%d", &insPlc);
printf("Input data for position %d: ", insPlc);
scanf("%d", &num1);
DlLinsertNodeAtAny(num1, insPlc);
a = 2;
displayDlList(a);
return 0;
}
// ฟังก์ชันสร้างลิสต์, แทรกหน้า, แทรกท้าย, แทรกกลาง, แสดงผล
// (โค้ดเต็มอยู่ในต้นฉบับ)
ผลลัพธ์ตัวอย่าง
Input number of nodes: 5 Input data for node 1: 23 Input data for node 2: 12 Input data for node 3: 11 Input data for node 4: 34 Input data for node 5: 10 Data entered: 23 12 11 34 10 Input position (1 to 6): 5 Input data for position 5: 78 After insertion: 23 12 11 34 78 10