Skip to content

Instantly share code, notes, and snippets.

@souparno
Created October 29, 2014 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souparno/280bb3bfb3a65ad1a283 to your computer and use it in GitHub Desktop.
Save souparno/280bb3bfb3a65ad1a283 to your computer and use it in GitHub Desktop.
linkedlist
import java.io.*;
class LinkedList {
Node last = null;
// function to create the link list
public void createList(int n) {
Node node = new Node();
node.value = n;
node.next = last;
last = node;
}
// function to print the list
public void printList() {
Node temp = this.last;
while (temp != null) {
System.out.println(temp.value);
temp = temp.next;
}
}
// function to count the number of nodes in the list
public int countNode() {
int count = 0;
Node temp = last;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
// function to re arrange the nodes in the list
public void rearrangeList(LinkedList linkedlist) {
Node temp = linkedlist.last;
switch (linkedlist.countNode() % 3) {
case 1:
Node node = temp;
this.createList(node.value);
temp = temp.next;
break;
case 2:
Node node2 = temp;
Node node1 = temp.next;
this.createList(node1.value);
this.createList(node2.value);
temp = (temp.next).next;
break;
}// end of switch
while (temp != null) {
Node node3 = temp;
Node node2 = temp.next;
Node node1 = (temp.next).next;
this.createList(node2.value);
this.createList(node3.value);
this.createList(node1.value);
temp = ((temp.next).next).next;
}// end of the while loop
}// end of function
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList linkedlist = new LinkedList();
System.out.println("*****LinkedList rearranging****");
System.out.println("*****Author ---> Bonnie ****");
System.out.println("*****PLEASE ENTER NUMER >=3 ****");
int n = 0;
do {
System.out.println("Input a number. *input 0 to stop");
n = Integer.parseInt(br.readLine());
if (n != 0) {
linkedlist.createList(n);
}
} while (n != 0);
System.out.println("=== the list after re-arranging ===");
LinkedList _linkedlist = new LinkedList();
_linkedlist.rearrangeList(linkedlist);
_linkedlist.printList();
}
}
class Node {
int value;
Node next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment