Circular Double Linked List


SUBMITTED BY: Guest

DATE: Nov. 23, 2013, 4:58 p.m.

FORMAT: Text only

SIZE: 2.8 kB

HITS: 856

  1. http://cur.lv/4x9e0 (Earn Bitcoins)
  2. class CircularDoubleLinkedList{
  3. public CircularDoubleLinkedList prev, next;
  4. public int value;
  5. public CircularDoubleLinkedList(int value){
  6. this.value = value;
  7. this.prev = this;
  8. this.next = this;
  9. //assert(this.checkStructure());
  10. }
  11. private CircularDoubleLinkedList(int value, CircularDoubleLinkedList prev, CircularDoubleLinkedList next){
  12. this.value = value;
  13. this.prev = prev;
  14. this.next = next;
  15. //assert(this.checkStructure());
  16. }
  17. public CircularDoubleLinkedList insert(int value){
  18. CircularDoubleLinkedList res = new CircularDoubleLinkedList(value);
  19. res.prev = this.prev;
  20. res.next = this;
  21. this.prev.next = res;
  22. this.prev = res;
  23. return res;
  24. }
  25. public int size(){
  26. int res = 1;
  27. CircularDoubleLinkedList tmp = this.next;
  28. while(!(tmp == this)){
  29. res++;
  30. tmp = tmp.next;
  31. }
  32. return res;
  33. }
  34. public boolean checkStructure(){
  35. CircularDoubleLinkedList tmpThisNext = this; //Laufvariable für die Vorgänger der Elemente
  36. CircularDoubleLinkedList tmpThis = this; // für die Abbruchbedingung
  37. if(tmpThis.next == null || tmpThis.prev == null){
  38. return false;
  39. }
  40. CircularDoubleLinkedList tmpPrev = this.prev; // für die letzte Überprüfung
  41. CircularDoubleLinkedList tmpNext = this.next; // Laufvariable für die Elemente
  42. while(!(tmpNext == tmpThis)){
  43. if(tmpNext.prev != tmpThisNext) return false;
  44. if(tmpNext.next == null) return false;
  45. if(tmpNext.next == this && tmpPrev != tmpNext) return false;
  46. tmpThisNext = tmpThisNext.next;
  47. tmpNext = tmpNext.next;
  48. }
  49. return true;
  50. }
  51. public static void main(String[] args){
  52. CircularDoubleLinkedList c1 = new CircularDoubleLinkedList(1);
  53. System.out.println(c1.size());
  54. System.out.println(c1.checkStructure());
  55. c1 = c1.insert(2);
  56. System.out.println(c1.size());
  57. System.out.println(c1.checkStructure());
  58. c1 = c1.insert(3);
  59. System.out.println(c1.size());
  60. System.out.println(c1.checkStructure());
  61. }
  62. }

comments powered by Disqus