Question

Using Python Create a simple linked list by defining a struct (in C/C++) or a class...

Using Python Create a simple linked list by defining a struct (in C/C++) or a class (in Python3). For example, in C/C++:
struct singly_linked_list
{
int data;
singly_linked_list *next;
};

(Make sure you understand the concept of pointers - or lack thereof - in Python.)

Write a function to determine if there is a cycle in the singly linked list. Return 1 if there is a cycle in the list, 0 if no cycle. This is a very common interview question. Think carefully about how to solve this. There are myriad solutions online which you should not consult

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#CODE IN PYTHON
class Node:
    def __init__(self, val = None):
        self.data = val
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert(self, val):
        if self.head == None:
            self.head = Node(val)
            self.tail = self.head
        else:
            self.tail.next = Node(val)
            self.tail = self.tail.next

    def print(self):
        ptr = self.head
        while ptr is not None:
            print(ptr.data, end = " ")
            ptr = ptr.next
        print()

    def isCycle(self):
        slowPtr = self.head# This will move one node at a time
        fastPtr = self.head# This will move two nodes at a time

        while slowPtr != None and fastPtr.next != None:
            slowPtr = slowPtr.next # Move past one node
            fastPtr = fastPtr.next.next # Move past two nodes
            if slowPtr == fastPtr: # If at any point of time both of them points to same node
                return 1 # Cycle is present
        return 0 # Cycle is not present

ll = LinkedList()
ll.insert("Monday")
ll.insert("Tuesday")
ll.insert("Wednesday")
ll.insert("Thursday")
ll.insert("Friday")
ll.insert("Saturday")
ll.insert("Sunday")

print("Linked list: ", end = "")
ll.print()
print("isCycle(): ", ll.isCycle())

print("Adding a cycle in the linked list...")
# Adding a cycle in the linked list
ll.tail.next = ll.head # Now next of tail points to head of the list
print("isCycle(): ", ll.isCycle())

OUTPUT:

FOR ANY DOUBT DROP A COMMENT

Add a comment
Know the answer?
Add Answer to:
Using Python Create a simple linked list by defining a struct (in C/C++) or a class...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • You are given a pointer to a singly linked list. The singly linked list has cycles...

    You are given a pointer to a singly linked list. The singly linked list has cycles due to a programming error. Write a C program to detect whether the linked list has cycles without storing all the pointers to the nodes. The function detect_cycles should return 1 when a cycle is found and 0 when there are no cycles. Your code should handle all corner cases carefully and should not cause segmentation fault. Figure shows various examples of cycles for...

  • C LINKED LIST #include <stdlib.h> #include <stdio.h> //Struct for a polynomial term (double linked list object)...

    C LINKED LIST #include <stdlib.h> #include <stdio.h> //Struct for a polynomial term (double linked list object) typedef struct Polynomial t_Polynomial; typedef struct Term { // coefficient of the polynomial term associated with the object int coef;    // power of the polynomial term associated with the object int power;    // pointer to the next object (to facilitate a doubly linked list) struct Term *next;    // pointer to the previous object (to facilitate a doubly linked list) struct Term...

  • I need help completing this with C++ /** * Definition for singly-linked list. * struct ListNode...

    I need help completing this with C++ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) {    } };

  • use python In class, we've studied Singly-Linked Lists which are made of nodes that point at...

    use python In class, we've studied Singly-Linked Lists which are made of nodes that point at subsequent nodes. One of the biggest annoyances with Linked Lists is the difficulty of going backwards through a list (such as getting the previous node or traversing the list backwards). An intuitive solution to this inefficiency is the doubly-linked list, which adds pointers to previ- ous nodes. Doubly-Linked Lists are not very different from Singly-Linked Lists, but are far more common because they are...

  • use python In class, we've studied Singly-Linked Lists which are made of nodes that point at...

    use python In class, we've studied Singly-Linked Lists which are made of nodes that point at subsequent nodes. One of the biggest annoyances with Linked Lists is the difficulty of going backwards through a list (such as getting the previous node or traversing the list backwards). An intuitive solution to this inefficiency is the doubly-linked list, which adds pointers to previ- ous nodes. Doubly-Linked Lists are not very different from Singly-Linked Lists, but are far more common because they are...

  • use python In class, we've studied Singly-Linked Lists which are made of nodes that point at...

    use python In class, we've studied Singly-Linked Lists which are made of nodes that point at subsequent nodes. One of the biggest annoyances with Linked Lists is the difficulty of going backwards through a list (such as getting the previous node or traversing the list backwards). An intuitive solution to this inefficiency is the doubly-linked list, which adds pointers to previ- ous nodes. Doubly-Linked Lists are not very different from Singly-Linked Lists, but are far more common because they are...

  • C++ function using templates and linked list. [Create a simple linked list class to use within...

    C++ function using templates and linked list. [Create a simple linked list class to use within the class queue.] template <class T> class Queue : linkedList { void EnqueueO1(T t) - adds t to the end of the queue. };

  • » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should impleme...

    Using C Please comment » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should implement the following functions that take a stack o void push(Stack * stack, int value) ● int pop(Stack * stack) Prompt the user to input 5 integers, and use the stack to reverse the integers Print the result to the screen. o o » Part B: Queue o Create a Queue struct that is a wrapper for...

  • Programing C Just with #include <stdio.h> We will create a singly linked list of 7 nodes....

    Programing C Just with #include <stdio.h> We will create a singly linked list of 7 nodes. Then, the user will tell us whether to print the “odd-placed” nodes or the “even-placed” nodes. For example, if I had a list of 5 nodes like below, and the user specifies for the odd nodes to be printed, my program would print the values in nodes nl and n3. If the user instead indicated for the even nodes to be printed, my program...

  • Write a Java class myLinkedList to simulate a singly linked list using arrays as the underlying...

    Write a Java class myLinkedList to simulate a singly linked list using arrays as the underlying structure. Include the following methods: 1. insert an element within the linked list.(this should also work for the front and the rear of the list) 2. Remove an element from the linked list 3. Display (print) the elements of the linked list in order. 4. A method to check if the list is "empty". Test your solution using a linked list that initially has...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT