Finding a Loop in a Singly Linked List

 

Motivation

A singly linked list is a common data structure familiar to all computer scientists. A singly linked list is made of nodes where each node has a pointer to the next node (or null to end the list). A singly linked list is often used as a stack (or last in first out queue (LIFO)) because adding a new first element, removing the existing first element, and examining the first element are very fast O(1) operations.
When working with singly linked list, you are typically given a link to the first node. Common operations on a singly linked list are iterating through all the nodes, adding to the list, or deleting from the list. Algorithms for these operations generally require a well formed linked list. That is a linked list without loops or cycles in it.
If a linked list has a cycle:
  • The malformed linked list has no end (no node ever has a null next_node pointer)
  • The malformed linked list contains two links to some node
  • Iterating through the malformed linked list will yield all nodes in the loop multiple times
A malformed linked list with a loop causes iteration over the list to fail because the iteration will never reach the end of the list. Therefore, it is desirable to be able to detect that a linked list is malformed before trying an iteration. This article is a discussion of various algorithms to detect a loop in a singly linked list.

 

Incorrect "Solutions"

Traverse the List Until the End

Just look at the entire list to see if it has and end. When it ends, return.
// Incorrect 'solution'
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  while (currentNode = currentNode.next());
  return false;
}
 
The problem with this solution is that if the linked list does have a loop, the program will never terminate. There is no way for this algorithm to return true when the linked list does have a loop.

Mark Each Node

Traverse the list and mark each node as having been seen. If you come to a node that has already been marked, then you know that the list has a loop.

// Incorrect 'solution'
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  do {
    if (currentNode.seen) return true;
    currentNode.seen = true;
  } while (currentNode = currentNode.next());
  return false;
}
 
The problem with this solution is ensuring that "seen" is marked as false for all the nodes before you start. If the linked list has a loop, it isn't possible to iterate over each node to set "seen" to "false" as an initial value for each node. It might be possible to overcome some of this by using a big integer rather than a boolean and using a random integer as your marker. In that case there is is a good chance that no node will have your inital value, but a small chance that one would and your algorithm would fail.
Even if you are able to solve the initial value problem, each node in a linked list may not have a field to use for this purpose. Requiring such a field in each node would mean that this is not a generic solution. As we will see later, this field is not needed for a perfectly correct and efficient solution anyway.

Detect Only Full Loops

When asked to come up with a solution, a common pitfall is not detecting all loops, but just a loop where the last node links to the first. A loop could still occur (and not be detected) if the last element linked to (for example) the second element.

// Incorrect 'solution'
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  while (currentNode = currentNode.next()){
    if (currentNode == startNode) return true;
  }
  return false;
}

 

Inefficient Solutions

Keep a hash set of all nodes seen so far

O(n) time complexity, O(n) space complexity
Keeping a set of all the nodes have seen so far and testing to see if the next node is in that set would be a perfectly correct solution. It would run fast as well. However it would use enough extra space to make a copy of the linked list. Allocating that much memory is prohibitively expensive for large lists.
 
// Inefficient solution
function boolean hasLoop(Node startNode){
  HashSet nodesSeen = new HashSet();
  Node currentNode = startNode;
  do {
    if (nodesSeen.contains(currentNode)) return true;
    nodesSeen.add(currentNode);
  } while (currentNode = currentNode.next());
  return false;
}
 

Use a doubly linked list

O(n) time complexity
Doubly linked lists make it easy to tell if there is a loop. If you encounter any node that doesn't link to the last node you visited, you know that there are two nodes linking to that node. Because the back links could be initially messed up in some other way, this algorithm is only correct if you can trust the back links. Otherwise it is just a malformed doubly linked list finder. The singly linked list can even be converted into a doubly linked list with little additional work. Again this will require that we change the structure of the Node to accomodate a second link. Something that may not be possible in all cases. Usually a singly linked list is used because the amount of space to allocate for each node is at a premium.
 
// Inefficient solution
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  Node previousNode = null;
  do {
    if (previousNode && currentNode.prev() && previousNode != currentNode.prev()) return true;
    if (!currentNode.prev()) currentNode.setPrev(previousNode);
    previousNode = currentNode;
  } while (currentNode = currentNode.next());
  return false;
}
 

Check the Entire List So Far

O(n^2) time complexity

For each node, assume that the portion of the list examined so for has no loops and check to see if the next node creates a loop by iterating again over the entire list up to that point.


 

 

 

 

 

 

Reverse the list

O(n) time complexity
If you reverse the list, and remember the inital node, you will know
that there is a cycle if you get back to the first node. While
efficient, this solution changes the list. Reversing the list twice
would put the list back in its initial state, however this solution is
not appropriate for multi-threaded applications. In some cases there
may not be a way to modify nodes. Since changing the nodes is not needed
to get the answer, this solution is not recommended.



 
// Solution modifies the list
function boolean hasLoop(Node startNode){
  Node previousNode = null;
  Node currentNode = startNode;
  Node nextNode;
  if (!currentNode.next()) return false;
  while(currentNode){
    nextNode = currentNode.next();
    currentNode.setNext(previousNode);
    previousNode = currentNode;
    currentNode = nextNode;
  }
  return (previousNode == startNode);
}
 
Credit for this solution goes to Piyush Srivastava.



Use Memory Allocation Information

O(n) time complexity in the amount of memory on the computer
Some programming languages allow you to see meta information about
each node -- the memory address at which it is allocated. Because each
node has a unique numeric address, it is possible to use this
information to detect cycles. For this algorithm, keep track of the
minimum memory address seen, the maximum memory address seen, and the
number of nodes seen. If more nodes have been seen than can fit in the
address space then some node must have been seen twice and there is a
cycle.


 
// Depends on size of available computer memory rather than size of list
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  int minAddress, int maxAddress = ¤tNode;
  int nodesSeen = 0;
  while(currentNode = currentNode.next()){
    nodesSeen++;
    if (¤tNode < minAddress) minAddress = ¤tNode;
    if (¤tNode > maxAddress) maxAddress = ¤tNode;
    if (maxAddress - minAddress < nodesSeen) return true;
  }
  return false;
}
 
This algorithm relies on being able to see memomory address
information. This is not possible to implement in some programming
languages such as Java that do not make this information available. It
is likely that the entire list will be allocated close together in
memory. In such a case the implementation will run close to the running
time of the length of the list. However, if the nodes in the list are
allocated over a large memory space, the runtime of this algorithm could
be much greater than some of the best solutions.


 

Best Solutions

Catch Larger and Larger Loops

O(n) time complexity
Always store some node to check. Occasionally reset this node to
avoid the "Detect Only Full Loops" problem. When resetting it, double
the amount of time before resetting it again.


 
// Good solution
function boolean hasLoop(Node startNode){
  Node currentNode = startNode;
  Node checkNode = null;
  int since = 0;
  int sinceScale = 2;
  do {
    if (checkNode == currentNode) return true;
    if (since >= sinceScale){
        checkNode = currentNode;
        since = 0;
        sinceScale = 2*sinceScale;
    }
    since++;
  } while (currentNode = currentNode.next());
  return false;
}
 
This solution is O(n) because sinceScale grows linearly with the
number of calls to next(). Once sinceScale is greater than the size of
the loop, another n calls to next() may be required to detect the loop.
This solution requires up to 3 traversals of the list.
This solution was devised by Stephen Ostermiller and proven O(n) by Daniel Martin.


Catch Loops in Two Passes

O(n) time complexity
Simultaneously go through the list by ones (slow iterator) and by
twos (fast iterator). If there is a loop the fast iterator will go
around that loop twice as fast as the slow iterator. The fast iterator
will lap the slow iterator within a single pass through the cycle.
Detecting a loop is then just detecting that the slow iterator has been
lapped by the fast iterator.


 
// Best solution
function boolean hasLoop(Node startNode){
  Node slowNode = Node fastNode1 = Node fastNode2 = startNode;
  while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){
    if (slowNode == fastNode1 || slowNode == fastNode2) return true;
    slowNode = slowNode.next();
  }
  return false;
}
 
This solution is "Floyd's Cycle-Finding Algorithm" as published in
"Non-deterministic Algorithms" by Robert W. Floyd in 1967. It is also
called "The Tortoise and the Hare Algorithm".


3D game Programming

if you are interested in 3D Graphics and game programming. i think you will like this book which i found by chance and i want to share it with people who are interested in game programming
the book name is: Mathematics for 3D Game Programming and Computer Graphics 2E 
the book link is:  http://www.mediafire.com/?fc3ximv4h3sjaa7
this is a good openGL book : http://fly.cc.fer.hr/~unreal/theredbook/
and please if anyone have any interesting materials that will help me, post it in comment please

Stone Age




The Stone Age is the first period of the three-age system of archaeology, it has been divided into three ages, the Paleolithic (2.5 million years ago), the Mesolithic (from around 8000 BC to 5000 BC), and the Neolithic (from around 5000 BC to 3800 BC)

Lets talk about these three ages in details …..

The Paleolithic Era is considered one of the longest and oldest ages in human beings, at this age the human underwent to natural authority, hunting, gathering plants, and scavenging wild animals was his main source of food, and he used tree branches and stone as hunting tools and also to defend himself.

Not only that but also he improved these tools so he invented knifes, combs, spears, and drills using stone.

And in the end of the age he was able to invent chisels, stone to grind up the grain and others with the effect of the red ocher, and also stoves and finally he discovered the fire which considered the most important discovery at this age, it has been helping him in the Mesolithic, Neolithic, Predynastic, and dynastic ages.
About this age’s manifestations it appeared in several places in the banks of the Nile valley, delta, desert valleys,  Abbasia area, Fayoum, around the old springs in oases specially the kharga oasis, the two plateaus (the eastern and  the western), and in several places in upper Egypt specially Teba.

The Mesolithic Era lasted for around 3000 years, there aren’t a lot of tools representing that age in Egypt.

Tools for hunting whales, arrowheads from zaran (Tapered stone), and manual scythes was found in kom-ambo, angabeya valley (in the south of Cairo - Suez road), and helwan.

There are a lot of researchers who don’t admit the existence of this age in Egypt because they believe that its industry was extension to the helwan spring and delta parties industry.

The site of Natovih (according to the Natov valley in the west of Jerusalem) civilization in Palestine is considered one of the most important sites which belong to Mesolithic and Neolithic civilization. And their manifestations were found at this site containing the period of food gathering and the manifestations of the start of the transition to stability. There also were stone tools, arrowheads, scythes, and mortars.
The Natovih civilization gathered in its sites between caves and extended squares in front of it especially in the area of Karml mountain and in Jordan’s river valley.

Finally, Neolithic Period (5000-3800 BC) also called New Stone Age final stage of cultural evolution or technological development among prehistoric humans. It was characterized by stone tools shaped by polishing or grinding, dependence on domesticated plants or animals, settlement in permanent villages, and the appearance of such crafts as pottery and weaving. The Neolithic followed the Paleolithic Period, or age of chipped-stone.
I will not be able to talk more about Neolithic right now so Thank You

Written BY: leckchess

Korean Alphabet (Hangeul)


Most English speakers think Korean has thousands of characters, like Chinese, but it actually has a very simple and logical alphabet, which you can learn in a few minutes. The alphabet was invented in 1443 during the reign of the Great King Sejong. There are 14 basic consonants and 10 basic vowels. Letters that have similar sounds also have similar shapes, so it is easy to learn.

Korean alphabet
You can hear how the letters are pronounced on other web sites, such as indiana.edu/~koreanrs/hangul.html.
The letters are grouped into syllable blocks containing an initial consonant (which may be silent or double), one or two vowels (below or to the right), and sometimes a final consonant (below).
Now, can you "decode" these words?
Try to write your name in Korean. You can look up your name in Korean on other websites, such as chinese-tools.com/names/korean.
You can find a lot more Korean on the web. Even if you are like me and don't know any Korean words, you can have still have fun "decoding" some words in a Korean text, such as words borrowed from English, the names of famous people, place names, and product brand names.

Japanese Animations


Anime and carton words

In Japan, the term anime does not specify an animation's nation of origin or style; instead, it serves as a blanket term to refer to all forms of animation from around the world.
English-language dictionaries define anime as "a Japanese style of motion-picture animation" or as "a style of animation developed in Japan".
In English, anime, when used as a common noun, normally functions as a mass noun (for example: "Do you watch anime?", "How much anime have you collected?"). However, in casual usage the word also appears as a count noun. Anime can also be used as a suppletive adjective or classifier noun ("The anime Guyver is different from the movie Guyver").
Non-Japanese works that borrow stylization from anime are commonly referred to as "anime-influenced animation (refers to non-Japanese works of animation that emulate certain aspects of the visual style of anime.)" but it is not unusual for a viewer who does not know the country of origin of such material to refer to it as simply "anime"
If you searched the internet also you will find a lot of people who says that there is no difference between both anime and cartoon but in my opinion and also I found it once on the internet……
Anime: represents real life somehow I mean if somebody dead that means he dead and he will not come back again (as tom and jerry)  - it aims for good story not only fun you can find anime that doesn’t contain any  comedy situations (as 12 kingdom).
Cartoon: represents virtual life that aims for laugh even if there are unbelievable situations (as Tom and Jerry) you can find cartoon characters stretches and shrinks and so on.

History

Anime began at the start of the 20th century, when Japanese filmmakers experimented with the animation techniques also pioneered in France, Germany, the United States, and Russia. The oldest known anime in existence first screened in 1917 – a two-minute clip of a samurai trying to test a new sword on his target, only to suffer defeat.
By the 1930s animation became an alternative format of storytelling to the live-action industry in Japan. But it suffered competition from foreign producers and many animators, such as Noburō Ōfuji ( Japanese film director) and Yasuji Murata ( pioneering animator who helped develop the art of anime in Japan) still worked in cheaper cutout not cel animation, although with masterful results.


Cutout animation                           Cel animation


watch video about cutout animation


Other creators, such as Kenzō Masaoka and Mitsuyo Seo, nonetheless made great strides in animation technique, especially with increasing help from a government using animation in education and propaganda.

The first talkie anime was Chikara to Onna no Yo no Naka, produced by Masaoka in 1933.


The first feature length animated film was Momotaro's Divine Sea Warriors directed by Seo in 1945 with sponsorship by the Imperial Japanese Navy.

The success of The Walt Disney Company's 1937 feature film Snow White and the Seven Dwarfs influenced Japanese animators. In the 1960s, manga artist and animator Osamu Tezuka adapted and simplified many Disney animation-techniques to reduce costs and to limit the number of frames in productions. He intended this as a temporary measure to allow him to produce material on a tight schedule with inexperienced animation-staff.

The 1970s saw a surge of growth in the popularity of manga – many of them later animated as death note – special A – narto – anuyosha - ……etc.








Japan and animation

Japan is a great animation world, a paradise for “anime” enthusiasts. Today, more and more world anime fans are flocking to Japan for an animation pilgrimage.
But now Japan became more creative than before it didn’t stop on creating animated movies but also now there is life concerts with animated singer












you can watch it here

World and anime

In the UK, many video shops will classify all adult-oriented animated videos in the "Anime" section for convenience, regardless of whether they show any stylistic similarities to Japanese animation. No evidence suggests that this has led to any change in the use of the word.



Programs to make anime characters

MikuMiku Dance

Anime Studio


3DS Max


Etc….


How to Type Chinese/Korean on Windows Vista/Windows 7


Simplified Chinese

1. Start-> Control Panel-> Clock, Language, and Region
2. Under Regional and Language Options click change keyboard or other input methods
3. Change Keyboards…-> Add-> Chinese (Simplified, PRC)-> Keyboard->  Chinese Simplified QuanPin (Version 6.0)-> OK
chinese1
4. Apply-> OK
5. Now you can type Chinese.  You have the option to show the language bar like this:
chinnese2
or hidden like this:
chinese3
6. To switch back from Chinese-English or English-Chinese you can
a) hold onto [alt] and [shift] together to switch the languages
b) or directly click the icon to change the keyboard language
7. If the setting is on Chinese and it won’t type Chinese, make sure you press [shift] once and try typing again
8. How to type Chinese: In order to get characters, you must type in pinyin.  For example: ni hao-> 你好
chinese4
chinese5
Type ni and enter 1 to get the correct ni, do the same for hao.  Since ni hao is a common term, you can type ni hao together:
chinese6
9. If you wish to remove the Chinese language keyboard, repeat 1-3, instead of add, click remove

Korean

1. Start-> Control Panel-> Clock, Language, and Region
2. Under Regional and Language Options click change keyboard or other input methods
3. Change Keyboards…-> Add-> Korean (Korea)-> Keyboard-> Microsoft (IME)  -> OK
korean1
4. Apply-> OK
5. You have the option to show the language bar like this:
korean2
or hidden:
korean3
6. You can type in Korean now! To switch back from Korean-English or English-Korean you can
a) hold onto [alt] and [shift] together to switch the languages
b) or click on the icon
7. Typing in Korean is a bit compicated campared to Chinese.  Make sure the Korean language bar look like this:
korean4
8. Here is a quick guide to type Korean letters on your keyboard:
korean5
and the letters means that
korean6

9. Let’s try writng Dong Bang Shin Ki in Korean:
e+h+d= 동
q+k+d= 방
t+l+s= 신
r+l= 기
e+h+d+q+k+d+t+l+s+r+l= 동방신기

for more information about korean letters please visit Korean Letters description

10. If you wish to remove the Korean language keyboard, repeat 1-3, instead of add, click remove