473,770 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check the linked list is circular or not?

40 New Member
please anyone tell me whether the following code works for checking the
linked list is circular or not?
Expand|Select|Wrap|Line Numbers
  1.    address 0        address1       address2
  2. | A|address1|     |B|address2|   |C|address0|
  3.    |                                          |
  4.    |                                          |
  5.   ptr1                                      ptr2
  6.  
  7.   A,B,C-are elements in list.
  8.   ptr1- points to first elt in list.
  9.   ptr2-points to last elt in list.
  10.  
  11.     if(ptr2+1 == ptr1)          
  12.     {
  13.        the list is circular.
  14.     }
Jun 4 '07 #1
12 15704
RedSon
5,000 Recognized Expert Expert
I'm going to have to go with... no.
Jun 4 '07 #2
RedSon
5,000 Recognized Expert Expert
The best way to figure out if a linked list is circular is to draw out your data structure on a piece of paper and pretend you are a computer. How can *you* tell if a list is circular?

Try drawing one that is circular and pretend you are a computer. Then draw one that is not circular and pretend you are a computer.

Usually if your last element points to your first element then it is circular. If you want to figure out if you have cycles then that is a complete separate issue.
Jun 4 '07 #3
Silent1Mezzo
208 New Member
please anyone tell me whether the following code works for checking the
linked list is circular or not?
Expand|Select|Wrap|Line Numbers
  1.    address 0        address1       address2
  2. | A|address1|     |B|address2|   |C|address0|
  3.    |                                          |
  4.    |                                          |
  5.   ptr1                                      ptr2
  6.  
  7.   A,B,C-are elements in list.
  8.   ptr1- points to first elt in list.
  9.   ptr2-points to last elt in list.
  10.  
  11.     if(ptr2+1 == ptr1)          
  12.     {
  13.        the list is circular.
  14.     }

The reason this doesn't work is because pointers are just addresses to the place where each node is located in memory.

So lets say the address of ptr1 is 0x12BC and the address of ptr2 is 0xB901. Even though they could be linked together their addresses are totally different (so the ptr1+1 will not work).

If its a small list you could store all of the pointers and then compare each pointer against the next node's pointer. This would be very tedious (lots of loops) and not very efficient but it would do the job.
Jun 4 '07 #4
Savage
1,764 Recognized Expert Top Contributor
The reason this doesn't work is because pointers are just addresses to the place where each node is located in memory.

So lets say the address of ptr1 is 0x12BC and the address of ptr2 is 0xB901. Even though they could be linked together their addresses are totally different (so the ptr1+1 will not work).

If its a small list you could store all of the pointers and then compare each pointer against the next node's pointer. This would be very tedious (lots of loops) and not very efficient but it would do the job.
And boring too.

One thing is sure OP needs to dereferance the pointers and test values that they realy point to,so:

if(ptr2->next==*ptr),sh ould be a way more closer to the solution.

Savage
Jun 4 '07 #5
RedSon
5,000 Recognized Expert Expert
And boring too.

One thing is sure OP needs to dereferance the pointers and test values that they realy point to,so:

if(ptr2->next==*ptr),sh ould be a way more closer to the solution.

Savage
Right but the question remains is what the OP wants is to see if the list is circular (ie. tail->next == head) or if there is a cycle (ie. node->next == visited node).

Telling if a list is circular is easy.

if (last_node->next == first_node) then its circular.
Jun 4 '07 #6
kky2k
34 New Member
Right but the question remains is what the OP wants is to see if the list is circular (ie. tail->next == head) or if there is a cycle (ie. node->next == visited node).

Telling if a list is circular is easy.

if (last_node->next == first_node) then its circular.

keep two pointers ptr1,ptr2
Expand|Select|Wrap|Line Numbers
  1.  
  2. ptr1(pointer)  increments by one step  ptr1 = HeadOfNode ;
  3. ptr2(pointer) increments by 2 steps     ptr2 = HeadOfNode -> NEXT;
  4.  
  5. while(ptr1 != NULL) //until it reaches EOL
  6. {
  7.  
  8.   if(pt1 == ptr2)  //if it is circular then at some point both the pointer will be same
  9. {
  10.     printf("VOILA ITS CIRCULAR OR HAVING LOOP");
  11.     return 0;
  12. }
  13.  else
  14. {
  15.  
  16. ptr1++;
  17. ptr2++;
  18.  
  19. }
  20. }
  21.  
Jun 5 '07 #7
RedSon
5,000 Recognized Expert Expert
keep two pointers ptr1,ptr2
Expand|Select|Wrap|Line Numbers
  1.  
  2. ptr1(pointer)  increments by one step  ptr1 = HeadOfNode ;
  3. ptr2(pointer) increments by 2 steps     ptr2 = HeadOfNode -> NEXT;
  4.  
  5. while(ptr1 != NULL) //until it reaches EOL
  6. {
  7.  
  8.   if(pt1 == ptr2)  //if it is circular then at some point both the pointer will be same
  9. {
  10.     printf("VOILA ITS CIRCULAR OR HAVING LOOP");
  11.     return 0;
  12. }
  13.  else
  14. {
  15.  
  16. ptr1++;
  17. ptr2++;
  18.  
  19. }
  20. }
  21.  
First off, thats not going to check if there is a cycle in your linked list because a cycle can occur anywhere not just in adjacent nodes. Second, its not going to check if the linked list is circular because at no point to you check to see if the last node points to the first node. Third, incrementing a pointer is not the same as following the link to the next node. Fourth, giving code (wrong or not) is not allowed for homework questions.
Jun 5 '07 #8
Gurmeet
7 New Member
Here the problem is list need not be circular such that last node point to the first node. List can be circular if last node point to any node in the list. Any other node except the last node can't make it circular, because node structure have only one next pointer. Also, here we don't know the last pointer, so can't do as lastPointer->next == firstPointer then circular.
I can think of two solutions in this case:
1) use of array which will contain the address of each node, scan the array for each node->next address, whether it's there in the array or not. if its there then list is circular and if the node->next reaches to NULL then list is not circular. Here problem is complexity of both time(O(n^2)) and of space.
2) Better solution is use of map if you are using C++(I don't know the equivalent in Java). Map will return false when key appears twice and over here key will be address of nodes.
Psudocode:
bool Fun(Struct Node* head){
Struct Node* temp=head;
while(temp!=NUL L)
{
if( map.insert(temp ,1) == false)
return true; //list is circular
temp=temp->next;
}
return false; //list is not circular
}

//I am not checking the code, might have some small mistake, take it as pseudocode
Jun 11 '07 #9
Girish Kanakagiri
93 New Member
please anyone tell me whether the following code works for checking the
linked list is circular or not?
Expand|Select|Wrap|Line Numbers
  1.    address 0        address1       address2
  2. | A|address1|     |B|address2|   |C|address0|
  3.    |                                          |
  4.    |                                          |
  5.   ptr1                                      ptr2
  6.  
  7.   A,B,C-are elements in list.
  8.   ptr1- points to first elt in list.
  9.   ptr2-points to last elt in list.
  10.  
  11.     if(ptr2+1 == ptr1)          
  12.     {
  13.        the list is circular.
  14.     }
It is not as complex as You are assuming.
1. Have ptr1 node pointing to head node.
2. Have a ptr2 node pointing to next of ptr1 node.
3. within While Loop with condition ptr2 not null compare
ptr1 and ptr2, if they are equal then print as Circular and break
increment the loop counter ptr2 to next node.

Is this clear ???

Regards,
Girish.
Jun 11 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

16
491
by: surender | last post by:
Hi, Let us think that we have 100 nodes in the single linked list. I have only 50th node address and i don't have the first node address but i want to print the 49th node data. So how can we print the 49th node data. Any body Pls help me. Thanks in advance
19
13576
by: RAJASEKHAR KONDABALA | last post by:
Hi, Does anybody know what the fastest way is to "search for a value in a singly-linked list from its tail" as oposed to its head? I am talking about a non-circular singly-linked list, i.e., head and tail are not connected. Of course, recursive function aproach to traverse the list is one way. But, depending upon the list size, it could overrun the stack pretty fast.
5
6061
by: John N. | last post by:
Hi All, Here I have a linked list each containing a char and is double linked. Then I have a pointer to an item in that list which is the current insertion point. In this funtion, the user hits the right and left keys to move this insertion point (cursor) Here is the problem:
9
4074
by: Goh, Yong Kwang | last post by:
I'm currently doing a project that has a array that supposed to be determined only at runtime. Originally, the prototype I did as a proof of theory (or a quick hack) So one method is to create a linked list and use malloc to create LinkedListNode as needed and use free() to destroy a node. But another easier way would be to use the realloc() function call to resize a memory block in the heap so that all the "nodes" are now consecutive...
7
2613
by: Kieran Simkin | last post by:
Hi all, I'm having some trouble with a linked list function and was wondering if anyone could shed any light on it. Basically I have a singly-linked list which stores pid numbers of a process's children - when a child is fork()ed its pid is added to the linked list. I then have a SIGCHLD handler which is supposed to remove the pid from the list when a child exits. The problem I'm having is that very very occasionally and seemingly...
14
2535
by: serge calderara | last post by:
Dear all, What is the proper way to check if two object are equal ? I do not mean equal on Object type only but also object value's thnaks for help regards serge
2
6452
by: sathishc58 | last post by:
Hi Can anyone explain me the difference between circular linked list and looped linked list? 1) In Circular linked list Next part of last node will be pointing to the first nodes starting address. 2) What is meant by loop then? Thanks & Regards Sathish Kumar
23
4375
by: Himanshu Chauhan | last post by:
Hi! I was wondering, In the first parse of a singly linked list of unknown length, is it possible to know when we are at middle of the linked list? Regards --Himanshu
12
4053
by: kalyan | last post by:
Hi, I am using Linux + SysV Shared memory (sorry, but my question is all about offset + pointers and not about linux/IPC) and hence use offset's instead on pointers to store the linked list in the shared memory. I run fedora 9 and gcc 4.2. I am able to insert values in to the list, remove values from the list, but the problem is in traversing the list. Atlease one or 2 list nodes disappear when traversing from the base of the list or...
0
9595
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10232
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10059
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9873
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8891
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7420
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.