ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่แบ่งรายการเชื่อมโยงที่กำหนดออกเป็นอัตราส่วน p:q
มันเป็นโปรแกรมตรงไปตรงมา มาดูขั้นตอนการแก้ปัญหากัน
-
สร้างโครงสร้างสำหรับโหนดรายการที่เชื่อมโยง
-
เริ่มต้นรายการที่เชื่อมโยงด้วยข้อมูลจำลอง
-
เริ่มต้นอัตราส่วน p:q
-
ค้นหาความยาวของรายการที่เชื่อมโยง
-
หากความยาวของรายการเชื่อมโยงน้อยกว่า p + q จะไม่สามารถแบ่งลิงก์เป็นอัตราส่วน p:q
-
อื่น ๆ วนซ้ำรายการที่เชื่อมโยงจนถึง p.
-
หลังจากการวนซ้ำ p ให้ลบลิงก์และสร้างส่วนหัวใหม่สำหรับรายการที่เชื่อมโยงที่สอง
-
ตอนนี้ ให้พิมพ์สองส่วนของรายการที่เชื่อมโยง
ตัวอย่าง
มาดูโค้ดกันเลย
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
void printLinkedList(Node* head) {
Node *temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
void splitLinkedList(Node *head, int p, int q) {
int n = 0;
Node *temp = head;
// finding the length of the linked list
while (temp != NULL) {
n += 1;
temp = temp->next;
}
// checking wether we can divide the linked list or not
if (p + q > n) {
cout << "Can't divide Linked list" << endl;
}
else {
temp = head;
while (p > 1) {
temp = temp->next;
p -= 1;
}
// second head node after splitting
Node *head_two = temp->next;
temp->next = NULL;
// printing linked lists
printLinkedList(head);
printLinkedList(head_two);
}
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = new Node(6);
int p = 2, q = 4;
splitLinkedList(head, p, q);
} ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
1 -> 2 -> NULL 3 -> 4 -> 5 -> 6 -> NULL
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น