public
class
Main {
public
static
void
main(String[] args) {
LinkedList linked_list =
new
LinkedList();
linked_list.insert(
1
);
linked_list.insert(
2
);
linked_list.insert(
3
);
linked_list.insert(
4
);
linked_list.insert(
5
);
System.out.print(
"Original Linked List: "
);
linked_list.display();
linked_list.move_first_to_end();
System.out.print(
"Modified Linked List: "
);
linked_list.display();
}
private
static
class
Node {
public
int
data;
public
Node next;
public
Node(
int
data) {
this
.data = data;
this
.next =
null
;
}
}
private
static
class
LinkedList {
public
Node head;
public
LinkedList() {
this
.head =
null
;
}
public
void
insert(
int
data) {
Node new_node =
new
Node(data);
if
(
this
.head ==
null
) {
this
.head = new_node;
}
else
{
Node current_node =
this
.head;
while
(current_node.next !=
null
) {
current_node = current_node.next;
}
current_node.next = new_node;
}
}
public
void
display() {
Node current_node =
this
.head;
while
(current_node !=
null
) {
System.out.print(current_node.data +
" "
);
current_node = current_node.next;
}
System.out.println();
}
public
Node move_first_to_end() {
if
(
this
.head ==
null
||
this
.head.next ==
null
) {
return
this
.head;
}
Node old_head =
this
.head;
this
.head =
this
.head.next;
Node current_node =
this
.head;
while
(current_node.next !=
null
) {
current_node = current_node.next;
}
current_node.next = old_head;
old_head.next =
null
;
return
this
.head;
}
}
}