Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class linkedlistdemo1 {
- static int[] data = new int[12];
- static int[] next = new int[12];
- static int HEAD, FREE;
- public static void initList() {
- int i;
- // -1 is used to indicate NULL pointer values
- HEAD = -1; // Empty List
- FREE = 0; // The free list starts with first node
- for (i=0; i<12; i++) {
- // initializes to nodes to 0
- // in fact any values can be used
- data[i] = 0;
- // initialize the free list
- // to include all nodes
- // FREE -> 0 -> 1 -> 2 -> 3 ..... 10 -> 11 -> -1
- next[i] = i+1;
- // The last node in the array
- if (i == 11) {
- next[i] = -1;
- }
- }
- }
- public static int getFreeNode() {
- int nodeID;
- // If there are available elements
- if (FREE != -1) {
- nodeID = FREE;
- FREE = next[FREE];
- } else {
- // Return -1
- // No more free nodes
- nodeID = -1;
- }
- return nodeID;
- }
- public static void returnFreeNode(int nodeID) {
- next[nodeID] = FREE;
- FREE = nodeID;
- }
- public static void removeBegin() {
- int temp;
- if (HEAD != -1) {
- temp = HEAD;
- HEAD = next[HEAD];
- returnFreeNode(temp);
- }
- }
- public static boolean insertAfter(int item, int pos){
- int temp;
- int count, prev, current;
- temp = getFreeNode();
- if (temp != -1) {
- if (pos == 0) {
- data[temp] = item;
- next[temp] = HEAD;
- HEAD = temp;
- return true;
- } else {
- count = 0;
- prev = HEAD;
- current = HEAD;
- while (current != -1 && count < pos) {
- prev = current;
- current = next[current];
- count++;
- }
- data[temp] = item;
- next[temp] = current;
- next[prev] = temp;
- return true;
- }
- } else
- return false;
- }
- public static boolean insertBegin(int item){
- return insertAfter(item, 0);
- }
- public static int countList() {
- int result=0;
- int current;
- current = HEAD;
- while (current != -1) {
- result++;
- current = next[current];
- }
- return result;
- }
- public static void printList() {
- int i;
- i = HEAD;
- System.out.print("HEAD -> ");
- while (i != -1) {
- System.out.printf("%d -> ", data[i]);
- i = next[i];
- }
- System.out.println("END");
- }
- public static void printFreeList() {
- int i;
- i = FREE;
- System.out.print("FREE -> ");
- while (i != -1) {
- System.out.printf("[%d] -> ", i);
- i = next[i];
- }
- System.out.println("END");
- }
- public static void main(String[] args) {
- initList();
- insertBegin(9);
- insertBegin(8);
- insertBegin(7);
- printList();
- System.out.printf("Number of elements: %d\n",countList());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement