[英]Reverse Singly Linked List Java, check whether circular
I implemented a singly linked list in Java. 我用Java实现了一个单链表。 I can reverse a singly linked list and check whether a given list is circular.
我可以反转单个链接列表,并检查给定列表是否为循环列表。 The interesting thing is I can reverse a circular list, too which is strange and interesting.
有趣的是,我也可以颠倒循环列表,这既奇怪又有趣。 Does it make sense to be able to reverse a circular list?Actually it should get reversed over and over again right?
能够反向发送循环列表是否有意义?实际上应该一次又一次地反向发送吗? At the moment my below code is able to reverse a circular list and terminates.
目前,我的下面代码可以反转循环列表并终止。 Is it correct?
这是正确的吗?
public class ListNode{
int value;
ListNode next;
public ListNode(int value, ListNode next){
this.value = value;
this.next = next;
}
public ListNode next(){
return next;
}
public void setNext(ListNode next){
this.next = next;
}
public int value(){
return value;
}
}
public class SinglyLinkedList {
private ListNode head;
public SinglyLinkedList(ListNode head){
this.head = head;
}
public void reverse(){
ListNode current = head;
head = null;
while (current!=null){
ListNode temp = current;
current = current.next;
temp.next = head;
head = temp;
}
}
public static boolean isCircular(SinglyLinkedList list){
ListNode counter1 = list.head;
ListNode counter2 = list.head;
while (counter1!=null && counter2!=null){
counter1 = counter1.next;
counter2 = counter2.next;
if (counter2.next!=null){
counter2 = counter2.next;
} else
return false;
if (counter1 == counter2)
return true;
}
return false;
}
public static void printSinglyLinkedList(ListNode head){
ListNode temp = head;
while(temp!=null){
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] s){
ListNode a4 = new ListNode(4, null);
ListNode a3 = new ListNode(3, a4);
ListNode a2 = new ListNode(2, a3);
ListNode a1 = new ListNode(1, a2);
a4.setNext(a1);
SinglyLinkedList list1 = new SinglyLinkedList(a1);
System.out.println(isCircular(list1));
if (!isCircular(list1))
printSinglyLinkedList(list1.head);
list1.reverse();
if (!isCircular(list1))
printSinglyLinkedList(list1.head);
}
}
a4.setNext(a1); a4.setNext(a1);
Remove the above statement. 删除上述声明。 This makes it circular.
这使其成为圆形。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.