Last active
May 12, 2019 15:05
-
-
Save salzig/bfc8abb90b445809d647e5d89a4b9beb to your computer and use it in GitHub Desktop.
Stupid Ring Linked List in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prints: (anker) C <- B <- A <- C <- B <- A | |
using System; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Ring ring = new Ring(); | |
ring.prepend("B"); | |
ring.prepend("C"); | |
System.Console.WriteLine(ring.printNodes(5)); | |
} | |
} | |
public class Ring { | |
public Node anker; | |
public Ring() { | |
anker = new Node("A"); | |
} | |
public void prepend(String name) { | |
Node old = anker; | |
anker = new Node(name, old); | |
nodeWithNext(old, old).next = anker; | |
} | |
// Finde Knoten der auf "next" zeigt. | |
public Node nodeWithNext(Node current, Node next) { | |
if (current.next != next) { return nodeWithNext(current.next, next); } | |
return current; | |
} | |
public String printNodes(int length) { | |
String result = ""; | |
Node node = anker; | |
result = "(anker) " + node.name; | |
for (int x = 0; x < length; x++) { | |
node = node.next; | |
result = result + " <- " + node.name; | |
} | |
return result; | |
} | |
} | |
public class Node { | |
public Node next; | |
public String name; | |
public Node(String name) { | |
this.next = this; | |
this.name = name; | |
} | |
public Node(String name, Node next) { | |
this.next = next; | |
this.name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment