ขั้นแรกให้เรากำหนดรายการเชื่อมโยงที่มีข้อมูลและตัวชี้ไปยังโหนดถัดไป
struct Node {
int data;
struct Node* next;
}; ต่อไป เราสร้างฟังก์ชัน createNode(int data) ที่รับข้อมูล int เป็นพารามิเตอร์และส่งกลับโหนดที่สร้างขึ้นใหม่หลังจากกำหนดค่าพารามิเตอร์ ตัวชี้ถัดไปที่โหนดจะเป็นโมฆะ
Node* createNode(int data){
struct Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
} ตอนนี้เรามีฟังก์ชั่น deleteMiddle(struct Node* head) ซึ่งรับรูทโหนด หากโหนดรูทไม่เป็นค่าว่าง มันก็จะกำหนดค่าถัดไปของโหนดก่อนหน้าถึงค่ากลางให้กับโหนดที่อยู่ถัดจากค่าตรงกลางและส่งกลับค่า temphead ซึ่งเป็นส่วนหัวที่แก้ไข
struct Node* deleteMiddle(struct Node* head){
if (head == NULL)
return NULL;
if (head->next == NULL) {
delete head;
return NULL;
}
Node* temphead = head;
int count = nodeCount(head);
int mid = count / 2;
while (mid-- > 1) {
head = head->next;
}
head->next = head->next->next;
return temphead;
} ในที่สุด เราก็มีฟังก์ชัน printList(Node *ptr) ซึ่งใช้ส่วนหัวของรายการและพิมพ์รายการ
void printList(Node * ptr){
while (ptr!= NULL) {
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL"<<endl;
} ตัวอย่าง
ให้เราดูการดำเนินการต่อไปนี้ของการลบตรงกลางของรายการที่เชื่อมโยงเดี่ยว
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
Node* createNode(int data){
struct Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int nodeCount(struct Node* head){
int count = 0;
while (head != NULL) {
head = head->next;
count++;
}
return count;
}
struct Node* deleteMiddle(struct Node* head){
if (head == NULL)
return NULL;
if (head->next == NULL) {
delete head;
return NULL;
}
Node* temphead = head;
int count = nodeCount(head);
int mid = count / 2;
while (mid-- > 1) {
head = head->next;
}
head->next = head->next->next;
return temphead;
}
void printList(Node * ptr){
while (ptr!= NULL) {
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL"<<endl;
}
int main(){
struct Node* head = createNode(2);
head->next = createNode(4);
head->next->next = createNode(6);
head->next->next->next = createNode(8);
head->next->next->next->next = createNode(10);
cout << "Original linked list"<<endl;
printList(head);
head = deleteMiddle(head);
cout<<endl;
cout << "After deleting the middle of the linked list"<<endl;
printList(head);
return 0;
} ผลลัพธ์
รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -
Original linked list 2->4->6->8->10->NULL After deleting the middle of the linked list 2->4->8->10->NULL