הפונקציות מהתוכנית הראשית
public static void printList(IntNode p){
while (p != null){
System.out.print(p.getValue()+",");
p = p.getNext();
}
System.out.println();
}
public static int sumList(IntNode p){
int sum = 0;
while (p != null){
sum += p.getValue();
p = p.getNext();
}
return sum;
}
public static IntNode last(IntNode p){
while (p.getNext() != null){
p = p.getNext();
}
return p;
}
public static void insertToList(IntNode p,int num){
IntNode q = new IntNode(num);
q.setNext(p.getNext());
p.setNext(q);
}
public static IntNode insertToListFirst(IntNode p ,int num){
IntNode q = new IntNode(num);
if (p != null){
q.setNext(p);
}
p = q;
return p;
}
public static void insertSeqToList(IntNode p,int num,int count){
// This function insert to the list the value num , count times
// at the end of the list
IntNode q = last(p);
for (int i=0;i<count;i++){
insertToList(q,num);
}
}
public static int countSeq(IntNode p,int num){
int count = 0;
while (p != null){
if (p.getValue() == num){
while (p.getNext() != null && p.getNext().getValue() == num){
p = p.getNext();
}
count++;
}
p = p.getNext();
}
return count;
}
public static boolean isInList(IntNode p,int num){
while (p != null){
if (p.getValue() == num)
return true;
p = p.getNext();
}
return false;
}
public static IntNode ex7(){
IntNode p = null;
int num;
for (int i=0;i<50;i++){
num = (int)(Math.random()*90)+10;
if ((num % 10 != num / 10) && (!isInList(p,num))){
p = insertToListFirst(p,num);
}
}
return p;
}
public static void main(String[] args) {
IntNode first = ex7();
printList(first);
}
המחלקה IntNode
public class IntNode {
private int value;
private IntNode next;
public IntNode(int value){
this.value = value;
this.next = null;
}
public IntNode(int value, IntNode next){
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public IntNode getNext() {
return next;
}
public void setNext(IntNode next) {
this.next = next;
}
public String toString(){
if (next == null){
return value+" –> null ";
}
return value+" –> ";
}
}