Created
April 22, 2012 00:48
-
-
Save gnarl/2440566 to your computer and use it in GitHub Desktop.
Circular Linked List
This file contains 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
/** | |
* NodeCircle is a demo class that implments a size N linked list of nodes. The | |
* last node is then set to point to the first node creating a circular linked | |
* list. The method removeEveryFifthNode then removes every fifth node starting | |
* from the first node while maintaining the cicular linked list. | |
*/ | |
public class NodeCircle | |
{ | |
public static void main(String[] argv) | |
{ | |
NodeCircle nc = new NodeCircle(); | |
try | |
{ | |
int nodeLength = Integer.parseInt(argv[0]); | |
nc.run(nodeLength); | |
} | |
catch(Exception e) | |
{ | |
System.out.println("Missed : " + e); | |
} | |
} | |
public void run(final int nodeLength) | |
{ | |
Node firstNode = new Node(0); | |
Node nextNode = firstNode; | |
for(int i = 1; i < nodeLength; i++) | |
{ | |
nextNode = nextNode.createNode(i); | |
} | |
nextNode.setNextNode(firstNode); | |
System.out.println(firstNode.printList()); | |
removeEveryFifthNode(firstNode); | |
System.out.println(firstNode.printList()); | |
} | |
public void removeEveryFifthNode(Node node) | |
{ | |
Node nextNode = node; | |
int i = 0; | |
while(nextNode.getNextNode() != node) | |
{ | |
if(i == 4) | |
{ | |
i = 0; | |
Node tmpNode = nextNode.getNextNode(); | |
nextNode.setNextNode(tmpNode.getNextNode()); | |
} else { | |
i++; | |
nextNode = nextNode.getNextNode(); | |
} | |
} | |
} | |
private class Node | |
{ | |
private Node next = null; | |
private final int value; | |
public Node(int value) | |
{ | |
this.value = value; | |
} | |
public Node createNode(int value) | |
{ | |
Node newNode = new Node(value); | |
this.next = newNode; | |
return newNode; | |
} | |
public void setNextNode(final Node nextNode) | |
{ | |
this.next = nextNode; | |
} | |
public Node getNextNode() | |
{ | |
return this.next; | |
} | |
public String toString() | |
{ | |
return "[ " + value + " ]"; | |
} | |
public String printList() | |
{ | |
StringBuffer buffer = new StringBuffer(); | |
buffer.append( this.toString() ); | |
Node nextNode = this.next; | |
while( nextNode != null && | |
nextNode != this ) | |
{ | |
buffer.append(" -> " + nextNode.toString()); | |
nextNode = nextNode.getNextNode(); | |
} | |
return buffer.toString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment