public static void traverse(LinkedListNode head) { if (head == null) return; StringBuffer buffer = new StringBuffer(); while (head != null) { buffer.append(head.getData() + "->"); // remember to move head = head.getNext(); } buffer.append("null"); System.out.println(buffer.toString()); }
/** Get data stored in tail node of list. */ public T getLast() { // set a LinkedListNode to get the current Node LinkedListNode<T> currentNode = head; // As long as there is a node with data after the current Node while (currentNode.getNext() != null) { // shift to set the next node as the current Node currentNode = currentNode.getNext(); } // When there is no node after the current Node return the data in the // current Node return currentNode.getData(); }
public static LinkedListNode NumbersAddition(LinkedListNode n1, LinkedListNode n2) { // number 1 and number 2 may not have the same number of digits. if (n1 == null || n2 == null) return null; LinkedListNode sumHead = null; LinkedListNode sumTail = null; int advance = 0; while (n1 != null || n2 != null) { int digitSum = 0; if (n1 != null && n2 != null) digitSum = n1.getData() + n2.getData() + advance; else if (n1 == null) digitSum = n2.getData() + advance; else digitSum = n1.getData() + advance; if (digitSum >= 10) { advance = 1; digitSum = digitSum % 10; } else { advance = 0; } LinkedListNode dSum = new LinkedListNode(); dSum.setData(digitSum); if (sumHead == null) sumHead = dSum; if (sumTail == null) { sumTail = dSum; } else { sumTail.setNext(dSum); sumTail = dSum; } // move n1 and n2 under certain conditions! if (n1 != null) n1 = n1.getNext(); if (n2 != null) n2 = n2.getNext(); } if (advance == 1) { LinkedListNode last = new LinkedListNode(); last.setData(advance); sumTail.setNext(last); sumTail = last; } return sumHead; }
/** Return a String representation of the list. */ public String toString() { // set a LinkedListNode to get the current Node LinkedListNode<T> currentNode = head; String s = "{"; // As long as there is a node with data after the current Node while (currentNode != null) { s = s + " " + currentNode.getData(); // shift to set the next node as the current Node currentNode = currentNode.getNext(); } // When there is no node after the current Node return the data in the // current Node s = s + "}"; System.out.println("The list is " + s); return s; }