logo

הוספה ברשימה מעגלית מקושרת יחידה

במאמר זה נלמד כיצד להכניס צומת לרשימה מקושרת מעגלית. הוספה היא פעולה בסיסית ברשימות מקושרות הכוללת הוספת צומת חדש לרשימה. ברשימה מעגלית מקושרת הצומת האחרון מתחבר בחזרה לצומת הראשון ויוצר לולאה.

ישנן ארבע דרכים עיקריות להוסיף פריטים:

  1. הוספה ברשימה ריקה
  2. הוספה בתחילת הרשימה
  3. הוספה בסוף הרשימה
  4. הוספה במיקום מסוים ברשימה

יתרונות השימוש במצביע זנב במקום מצביע ראש

אנחנו צריכים לעבור את כל הרשימה כדי להוסיף צומת בהתחלה. גם להכנסה בסוף יש לעבור על כל הרשימה. אם במקום ה הַתחָלָה מצביע אנחנו לוקחים מצביע לצומת האחרון ואז בשני המקרים לא יהיה צורך לעבור את כל הרשימה. אז הוספה בהתחלה או בסוף לוקחת זמן קבוע ללא קשר לאורך הרשימה.



1. הוספה לרשימה ריקה ברשימה המקושרת המעגלית

כדי להוסיף צומת ברשימה מעגלית ריקה יוצר א צומת חדש עם הנתונים הנתונים מגדיר את המצביע הבא שלו להצביע על עצמו ומעדכן את אַחֲרוֹן מצביע להתייחס לזה צומת חדש .

הכנסה-ברשימה-ריקה-ברשימה-מקושרת-מעגלית' title=הוספה לרשימה ריקה

גישה צעד אחר צעד:

  • בדוק אם אַחֲרוֹן אינו nullptr . אִם נָכוֹן לַחֲזוֹר אַחֲרוֹן (הרשימה לא ריקה).
  • אחרת צור א צומת חדש עם הנתונים שסופקו.
    • הגדר את צומתים חדשים המצביע הבא יצביע על עצמו (קישור מעגלי).
    • לְעַדְכֵּן אַחֲרוֹן להצביע על צומת חדש ולהחזיר אותו.

לקריאה נוספת על הכנסה ברשימה ריקה עיין: הוספה לרשימה ריקה ברשימה המקושרת המעגלית

2. הכנסה בהתחלה ברשימה מקושרת מעגלית

כדי להוסיף צומת חדש בתחילת רשימה מעגלית מקושרת

  • אנו יוצרים תחילה את צומת חדש ולהקצות לזה זיכרון.
  • אם הרשימה ריקה (מסומן על ידי המצביע האחרון בָּטֵל ) אנחנו עושים את צומת חדש להצביע על עצמו.
  • אם הרשימה כבר מכילה צמתים אז אנחנו מגדירים את צומתים חדשים המצביע הבא להצביע על ראש נוכחי של הרשימה (כלומר אחרון->הבא )
  • לאחר מכן עדכן את המצביע הבא של הצומת האחרון כך שיצביע על צומת חדש . זה שומר על המבנה המעגלי של הרשימה.
הכנסה-בתחילת-הרשימה-מקושרת-מעגלית' loading='lazy' title=הכנסה בהתחלה ברשימה מקושרת מעגלית

לקריאה נוספת על הכנסה בהתחלה עיין: הכנסה בהתחלה ברשימה מקושרת מעגלית

3. הכנסה בסוף ברשימה מקושרת מעגלית

כדי להכניס צומת חדש בסוף רשימה מקושרת מעגלית אנו יוצרים תחילה את הצומת החדש ומקצים לו זיכרון.

  • אם הרשימה ריקה (ממוצע אַחֲרוֹן אוֹ זָנָב הוויה מצביע בָּטֵל ) אנו מאתחלים את הרשימה עם ה- צומת חדש ולגרום לו להצביע על עצמו כדי ליצור מבנה מעגלי.
  • אם הרשימה כבר מכילה צמתים אז אנחנו מגדירים את צומתים חדשים המצביע הבא להצביע על ראש נוכחי (שזה זנב->הבא )
  • לאחר מכן עדכן את הזנב הנוכחי המצביע הבא להצביע על צומת חדש .
  • לבסוף אנו מעדכנים את מצביע זנב אל ה צומת חדש.
  • זה יבטיח כי צומת חדש הוא כעת ה הצומת האחרון ברשימה תוך שמירה על ההצמדה המעגלי.
הכנסה-בסוף-הרשימה-מקושרת-חוזר' loading='lazy' title=הכנסה בסוף ברשימה מקושרת מעגלית

לקריאה נוספת על הכנסה בסוף עיין: הכנסה בסוף ברשימה מקושרת מעגלית

4. הכנסה במיקום ספציפי ברשימה מקושרת מעגלית

כדי להכניס צומת חדש במיקום ספציפי ברשימה מקושרת מעגלית, נבדוק תחילה אם הרשימה ריקה.

  • אם זה וה מַצָב אינו 1 לאחר מכן אנו מדפיסים הודעת שגיאה מכיוון שהמיקום אינו קיים ברשימה. אֲנִי
  • f ה מַצָב הוא 1 ואז אנחנו יוצרים את צומת חדש ולגרום לזה להצביע על עצמו.
  • אם הרשימה לא ריקה אנו יוצרים את ה צומת חדש וחצו את הרשימה כדי למצוא את נקודת ההכנסה הנכונה.
  • אם ה מַצָב הוא 1 אנו מכניסים את צומת חדש בהתחלה על ידי התאמת המצביעים בהתאם.
  • עבור עמדות אחרות אנו עוברים דרך הרשימה עד שנגיע למיקום הרצוי והכנסת צומת חדש על ידי עדכון המצביעים.
  • אם הצומת החדש מוכנס בסוף אנחנו גם מעדכנים את אַחֲרוֹן מצביע להפניה לצומת החדש השומר על המבנה המעגלי של הרשימה.
הכנסה-במיקום-ספציפי-של-רשימה-מעגלית-מקושרת' loading='lazy' title=הכנסה במיקום ספציפי ברשימה מקושרת מעגלית

גישה צעד אחר צעד:

  • אִם אַחֲרוֹן הוא nullptr ו pos אינו 1 להדפיס ' מיקום לא חוקי! '.
  • אחרת צור צומת חדש עם נתונים נתונים.
  • הוסף בהתחלה: אם pos הוא 1 עדכן מצביעים והחזר אחרון.
  • רשימת חצות: לולאה כדי למצוא את נקודת ההכנסה; הדפס 'מיקום לא חוקי!' אם מחוץ לתחום.
  • הכנס צומת: עדכן מצביעים כדי להוסיף את הצומת החדש.
  • עדכון אחרון: אם הוכנס בסוף העדכון אַחֲרוֹן .
C++
#include    using namespace std; struct Node{  int data;  Node *next;  Node(int value){  data = value;  next = nullptr;  } }; // Function to insert a node at a specific position in a circular linked list Node *insertAtPosition(Node *last int data int pos){  if (last == nullptr){  // If the list is empty  if (pos != 1){  cout << 'Invalid position!' << endl;  return last;  }  // Create a new node and make it point to itself  Node *newNode = new Node(data);  last = newNode;  last->next = last;  return last;  }  // Create a new node with the given data  Node *newNode = new Node(data);  // curr will point to head initially  Node *curr = last->next;  if (pos == 1){  // Insert at the beginning  newNode->next = curr;  last->next = newNode;  return last;  }  // Traverse the list to find the insertion point  for (int i = 1; i < pos - 1; ++i) {  curr = curr->next;    // If position is out of bounds  if (curr == last->next){  cout << 'Invalid position!' << endl;  return last;  }  }  // Insert the new node at the desired position  newNode->next = curr->next;  curr->next = newNode;  // Update last if the new node is inserted at the end  if (curr == last) last = newNode;  return last; } void printList(Node *last){  if (last == NULL) return;  Node *head = last->next;  while (true){  cout << head->data << ' ';  head = head->next;  if (head == last->next) break;  }  cout << endl; } int main(){  // Create circular linked list: 2 3 4  Node *first = new Node(2);  first->next = new Node(3);  first->next->next = new Node(4);  Node *last = first->next->next;  last->next = first;  cout << 'Original list: ';  printList(last);  // Insert elements at specific positions  int data = 5 pos = 2;  last = insertAtPosition(last data pos);  cout << 'List after insertions: ';  printList(last);  return 0; } 
C
#include  #include  // Define the Node structure struct Node {  int data;  struct Node *next; }; struct Node* createNode(int value); // Function to insert a node at a specific position in a circular linked list struct Node* insertAtPosition(struct Node *last int data int pos) {  if (last == NULL) {  // If the list is empty  if (pos != 1) {  printf('Invalid position!n');  return last;  }  // Create a new node and make it point to itself  struct Node *newNode = createNode(data);  last = newNode;  last->next = last;  return last;  }  // Create a new node with the given data  struct Node *newNode = createNode(data);  // curr will point to head initially  struct Node *curr = last->next;  if (pos == 1) {  // Insert at the beginning  newNode->next = curr;  last->next = newNode;  return last;  }  // Traverse the list to find the insertion point  for (int i = 1; i < pos - 1; ++i) {  curr = curr->next;  // If position is out of bounds  if (curr == last->next) {  printf('Invalid position!n');  return last;  }  }  // Insert the new node at the desired position  newNode->next = curr->next;  curr->next = newNode;  // Update last if the new node is inserted at the end  if (curr == last) last = newNode;  return last; } // Function to print the circular linked list void printList(struct Node *last) {  if (last == NULL) return;  struct Node *head = last->next;  while (1) {  printf('%d ' head->data);  head = head->next;  if (head == last->next) break;  }  printf('n'); } // Function to create a new node struct Node* createNode(int value) {  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));  newNode->data = value;  newNode->next = NULL;  return newNode; } int main() {  // Create circular linked list: 2 3 4  struct Node *first = createNode(2);  first->next = createNode(3);  first->next->next = createNode(4);  struct Node *last = first->next->next;  last->next = first;  printf('Original list: ');  printList(last);  // Insert elements at specific positions  int data = 5 pos = 2;  last = insertAtPosition(last data pos);  printf('List after insertions: ');  printList(last);  return 0; } 
Java
class Node {  int data;  Node next;  Node(int value){  data = value;  next = null;  } } public class GFG {  // Function to insert a node at a specific position in a  // circular linked list  static Node insertAtPosition(Node last int data  int pos){  if (last == null) {  // If the list is empty  if (pos != 1) {  System.out.println('Invalid position!');  return last;  }  // Create a new node and make it point to itself  Node newNode = new Node(data);  last = newNode;  last.next = last;  return last;  }  // Create a new node with the given data  Node newNode = new Node(data);  // curr will point to head initially  Node curr = last.next;  if (pos == 1) {  // Insert at the beginning  newNode.next = curr;  last.next = newNode;  return last;  }  // Traverse the list to find the insertion point  for (int i = 1; i < pos - 1; ++i) {  curr = curr.next;  // If position is out of bounds  if (curr == last.next) {  System.out.println('Invalid position!');  return last;  }  }  // Insert the new node at the desired position  newNode.next = curr.next;  curr.next = newNode;  // Update last if the new node is inserted at the  // end  if (curr == last)  last = newNode;  return last;  }  static void printList(Node last){  if (last == null)  return;  Node head = last.next;  while (true) {  System.out.print(head.data + ' ');  head = head.next;  if (head == last.next)  break;  }  System.out.println();  }  public static void main(String[] args)  {  // Create circular linked list: 2 3 4  Node first = new Node(2);  first.next = new Node(3);  first.next.next = new Node(4);  Node last = first.next.next;  last.next = first;  System.out.print('Original list: ');  printList(last);  // Insert elements at specific positions  int data = 5 pos = 2;  last = insertAtPosition(last data pos);  System.out.print('List after insertions: ');  printList(last);  } } 
Python
class Node: def __init__(self value): self.data = value self.next = None # Function to insert a node at a specific position in a circular linked list def insertAtPosition(last data pos): if last is None: # If the list is empty if pos != 1: print('Invalid position!') return last # Create a new node and make it point to itself new_node = Node(data) last = new_node last.next = last return last # Create a new node with the given data new_node = Node(data) # curr will point to head initially curr = last.next if pos == 1: # Insert at the beginning new_node.next = curr last.next = new_node return last # Traverse the list to find the insertion point for i in range(1 pos - 1): curr = curr.next # If position is out of bounds if curr == last.next: print('Invalid position!') return last # Insert the new node at the desired position new_node.next = curr.next curr.next = new_node # Update last if the new node is inserted at the end if curr == last: last = new_node return last # Function to print the circular linked list def print_list(last): if last is None: return head = last.next while True: print(head.data end=' ') head = head.next if head == last.next: break print() if __name__ == '__main__': # Create circular linked list: 2 3 4 first = Node(2) first.next = Node(3) first.next.next = Node(4) last = first.next.next last.next = first print('Original list: ' end='') print_list(last) # Insert elements at specific positions data = 5 pos = 2 last = insertAtPosition(last data pos) print('List after insertions: ' end='') print_list(last) 
JavaScript
class Node {  constructor(value){  this.data = value;  this.next = null;  } } // Function to insert a node at a specific position in a // circular linked list function insertAtPosition(last data pos) {  if (last === null) {  // If the list is empty  if (pos !== 1) {  console.log('Invalid position!');  return last;  }  // Create a new node and make it point to itself  let newNode = new Node(data);  last = newNode;  last.next = last;  return last;  }  // Create a new node with the given data  let newNode = new Node(data);  // curr will point to head initially  let curr = last.next;  if (pos === 1) {  // Insert at the beginning  newNode.next = curr;  last.next = newNode;  return last;  }  // Traverse the list to find the insertion point  for (let i = 1; i < pos - 1; ++i) {  curr = curr.next;  // If position is out of bounds  if (curr === last.next) {  console.log('Invalid position!');  return last;  }  }  // Insert the new node at the desired position  newNode.next = curr.next;  curr.next = newNode;  // Update last if the new node is inserted at the end  if (curr === last)  last = newNode;  return last; } // Function to print the circular linked list function printList(last){  if (last === null)  return;  let head = last.next;  while (true) {  console.log(head.data + ' ');  head = head.next;  if (head === last.next)  break;  }  console.log(); } // Create circular linked list: 2 3 4 let first = new Node(2); first.next = new Node(3); first.next.next = new Node(4); let last = first.next.next; last.next = first; console.log('Original list: '); printList(last); // Insert elements at specific positions let data = 5; let pos = 2; last = insertAtPosition(last data pos); console.log('List after insertions: '); printList(last); 

תְפוּקָה
Original list: 2 3 4 List after insertions: 2 5 3 4 

מורכבות זמן: O(n) עלינו לעבור את הרשימה כדי למצוא את המיקום הספציפי.
מרחב עזר: O(1)


צור חידון