Deletion and Reverse in Circular Linked List | GeekForGeeks | Problem of the Day

Поділитися
Вставка
  • Опубліковано 4 жов 2024

КОМЕНТАРІ • 3

  • @mathematics3398
    @mathematics3398  21 годину тому

    Table of Contents
    0:00 Problem Statement
    0:35 Solution - Deletion
    4:25 Solution - Reverse
    7:30 Pseudo Code - Deletion
    12:47 Pseudo Code - Reverse
    14:59 Code - Python
    17:19 Code - C++

  • @mathematics3398
    @mathematics3398  21 годину тому +1

    class Solution {
    public:
    // Function to reverse a circular linked list
    Node* reverse(Node* head) {
    if (!head)
    return head;
    if (head->next == head)
    return head;
    Node *prvs = NULL;
    Node *last = head;
    while (head->next != last) {
    Node *NEXT = head->next;
    head->next = prvs;
    prvs = head;
    head = NEXT;
    }
    head->next = prvs;
    prvs = head;
    last->next = prvs;
    return prvs;
    }
    // Function to delete a node from the circular linked list
    Node* deleteNode(Node* head, int key) {
    if (!head or head->next == head)
    return NULL;
    Node *ptr2 = head;
    Node *prvs = NULL;
    Node *ptr = head;
    while(ptr->data != key and ptr->next != head) {
    prvs = ptr;
    ptr = ptr->next;
    }
    // return if key not found
    if (ptr->data != key)
    return head;
    if (!prvs) {
    while (ptr2->next != head) {
    prvs = ptr2;
    ptr2 = ptr2->next;
    }
    prvs = ptr2;
    }
    prvs->next = ptr->next;
    if (ptr == head) {
    return ptr->next;
    }
    return head;
    }
    };

  • @mathematics3398
    @mathematics3398  21 годину тому

    class Solution:
    # Function to reverse a circular linked list
    def reverse(self, head):
    if not head or head.next == head:
    return head
    prvs = None
    last = head
    while head.next != last:
    NEXT = head.next
    head.next = prvs
    prvs = head
    head = NEXT
    head.next = prvs
    prvs = head
    last.next = prvs
    return prvs
    # Function to delete a node from the circular linked list
    def deleteNode(self, head, key):
    if not head or head.next == head:
    return None
    ptr1 = ptr2 = head
    prvs = None
    while ptr1.data != key and ptr1.next != head:
    prvs = ptr1
    ptr1 = ptr1.next
    if ptr1.data != key:
    return head
    if not prvs:
    while ptr2.next != head:
    ptr2 = ptr2.next
    prvs = ptr2
    prvs.next = ptr1.next
    if ptr1 == head:
    return ptr1.next
    return head