Want to add a element in desired index. But adding last - java

I use add method to add an element to a desired index. But it is adding last. I want to add an element to a desired index. How can do it with this. Is is possible? without end pointer.
import java.util.*;
class List {
Customer listPtr;
int index;
public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}
public void add(int index, Customer customer) {
int size = size();
while (size != -1) {
size--;
if (size == index) {
System.out.println(size + ":" + index);
add(customer);
}
}
}
public void removeFirst() {
Customer temp = listPtr;
if (listPtr != null) {
listPtr = temp.next;
}
}
public void removeLast() {
Customer temp = listPtr;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
index--;
}
public void removeAll() {
Customer temp = listPtr;
while (temp != null) {
listPtr = temp.next;
temp = temp.next;
}
}
public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
size++;
temp = temp.next;
}
return size;
}
public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class DemoList {
public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "Sam");
Customer c2 = new Customer("10012", "Jason");
Customer c3 = new Customer("10013", "Arnold");
Customer c4 = new Customer("10014", "Bob");
Customer c5 = new Customer("10015", "Tom");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
list.add(2, c5);
System.out.println(list.size());
list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " : " + name;
}
public boolean equals(Object ob) {
Customer c = (Customer) ob;
return this.id.equals(c.id);
}
}

Try this, finds index from the beginning and adds customer at that position
public void add(int index, Customer customer) {
int size = size();
Customer tmp=listPtr,tmp2;
int i=0;
//some boundary cases
if((index<0) ||(index>size)){
return;
}
//assumes all other cases are handled
while (i != size) {
if ((i+1) == index) {
System.out.println(size + ":" + index);
tmp2=tmp.next;
tmp.next=customer;
customer.next=tmp2;
break;
}
tmp=tmp.next;
++i;
}
}

Suppose you have two Customers, a, and b, and they are hooked up together.
Customer a = new Customer("a", "John");
Customer b = new Customer("b", "George");
a.next = b;
Now, you want to slip c between them:
Customer c = new Customer("c", "Paul");
You want eventually to have a.next == c and c.next == b. But if you make those changes in the wrong order, your list will have b detached from the rest of the list, and it will be garbage collected. So, do things in the correct order so nothing is lost:
c.next = b; // Now, both a.next and c.next == b.
a.next = c; // Finishing the splice. Now, a.next == c and c.next == b.
To insert items into the list, advance from the beginningindex places.
Customer nth(int n) {
Customer cust = listPtr;
for (int i = 0; i < n; ++i) {
cust = cust.next; // can lead to an NPE; you add the error checking.
}
return cust;
}
Now, get the nth customer, and splice a new one in. Again, watch out for NPEs.

Related

Polynomial Addition using Linked Lists // Java

I have an assignment for my Data Structures class. In the assignment, we have to implement polynomial addition using linked lists. I think I have it down but eclipse is giving me a null pointer exception. My problem is with the add method, though I included the whole class for context. Multiply I will tackle after.. Please help.
class PolynomialLinkedList{
private static class PNode{
private int coe;
private int exp;
private PNode next;
public PNode(int c, int e){
this(c, e, null);
}
public PNode(int c, int e, PNode n){
coe = c;
exp = e;
next = n;
}
public void setCoe(int c){ coe = c;}
public void setExp(int e){ exp = e;}
public void setNext(PNode n){ next = n;}
public int getCoe(){ return coe;}
public int getExp(){ return exp;}
public PNode getNext(){ return next;}
}
private PNode first;
private PNode last;
public PolynomialLinkedList(){
first = last = null;
}
public PolynomialLinkedList(int c, int e){
PNode tempn = new PNode(c, e);
first = last = tempn;
}
public void print(){
if (first == null){
System.out.println();
return;
}
PNode temp = first;
String ans = "";
while (temp != null){
if (temp.getCoe() > 0) {
if (temp != first) ans = ans + " + ";
ans = ans + temp.getCoe();
}
else if (temp.getCoe() < 0) ans = ans + " - " + temp.getCoe() * -1;
if (temp.getExp() != 0){
ans = ans + "X^" + temp.getExp();
}
temp = temp.getNext();
}
System.out.println(ans);
}
public PolynomialLinkedList add(PolynomialLinkedList s){
PolynomialLinkedList sum = new PolynomialLinkedList();
PNode temp1 = this.first;
PNode temp2 = s.first;
PNode tempAns = new PNode(0,0);
if(temp1.exp != temp2.exp) {
while(temp1.exp > temp2.exp) {
tempAns.setCoe(temp1.coe);
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
tempAns = sum.first.getNext();
}
while(temp1.exp < temp2.exp) {
tempAns.setCoe(temp2.coe);
tempAns.setExp(temp2.exp);
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
else if(temp1.exp == temp2.exp) {
while(temp1.exp == temp2.exp) {
tempAns.setCoe((temp1.coe + temp2.coe));
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
return sum;
}
public PolynomialLinkedList multiply(PolynomialLinkedList s){
PolynomialLinkedList product = new PolynomialLinkedList();
//implement this method
return product;
}
}

Output( ) from a Set class with Singly Linked List Hash Table

I have code that I have been working on going on 10 hours now, and for the life of me, I am unable to get the output( ) of my Set.java to work. Unfortunately I am not allowed to just import the Iterator or HashTable classes from java library. Any ideas or advice would really help.
public class SLL {
public class Node {
private int data;
private Node next;
public Node() {
data = 0;
next = null;
}
public Node(int newData, Node linkValue) {
data = newData;
next = linkValue;
}
public int getData() {
return data;
}
public Node getLink() {
return next;
}
} // End of Node inner class
private Node head;
public SLL() {
head = null;
}
public void addToStart(int itemData) {
head = new Node(itemData, head);
}
public boolean contains(int item) {
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a reference
* to that node. If target is not in the list, null is returned.
*/
public Node find(int target) {
Node position = head;
int itemAtPosition;
while (position != null) {
itemAtPosition = position.data;
if (itemAtPosition == target) {
return position;
}
position = position.next;
}
return null; // target was not found
}
public void outputList() {
Node position = head;
while (position != null) {
System.out.print(position.data + " ");
position = position.next;
}
System.out.println();
}
}
This is the class that I have been working on:
public class Set {
private SLL[] hashArray; // DO NOT MODIFY THIS LINE
private int size = 10; // DO NOT MODIFY THIS LINE
// DO NOT MODIFY THIS METHOD
public Set() {
hashArray = new SLL[size];
}
// DO NOT MODIFY THIS METHOD
private int computeHash(int s) {
return s % size;
}
// COMPLETE BELOW
public void add(int x)
{
int hash = computeHash(x); // Get hash value
SLL list = hashArray[hash];
if(hashArray[hash] == null)
hashArray[hash] = new SLL();
else if(!list.contains(x));
{
// Only add the target if it's not already
// on the list.
hashArray[hash].addToStart(x);
}
}
public void output()
{
SLL tmp = new SLL();
SLL.Node temp = tmp.head;
for(int i = 0; i < size; i++)
{
if(temp == null)
//I think a new instance needs to be created
while(temp.getLink() != null)
{
System.out.println(i + temp.getData() + toString() + " ");
}
}
}
}
And this is the tester it should work with:
public class Tester{
// Have this method to display your name, instead.
static void displayName(){
System.out.println("Program written by Tony.\n");
}
// DO NOT MODIFY THE MAIN METHOD
public static void main(String[] args){
displayName();
Set set1 = new Set();
Set set2 = new Set();
set1.add(3);
set1.add(3);
set1.add(13);
set1.add(23);
set1.add(4);
set1.add(5);
set2.add(15);
set2.add(6);
set2.add(6);
System.out.println("Contents of set 'set1': ");
set1.output();
System.out.println("Contents of set 'set2': ");
set2.output();
System.out.println();
}
}
You need to iterate through the entries in your hash array, and for each non-null entry, iterate through the linked list:
public void output() {
for (int i = 0; i < hashArray.length; i++) {
if (hahArray[i] != null) {
hashArray[i].outputList();
}
}
}
In your for loop as below:
if(temp == null)
//I think a new instance needs to be created
while(temp.getLink() != null)
{
System.out.println(i + temp.getData() + toString() + " ");
}
You should be checking temp != null and you are not moving your node from one to other to traverse over each elements. So you should change it to:
while(temp != null) {
System.out.println(temp.getData() + " ");
temp = temp.getLink();
}
So changing the output( ) a bit to
public void output()
{
SLL tmp = new SLL();
SLL.Node temp = tmp.head;
for (SLL s : hashArray) {
System.out.println(toString() + " " + s);}
}
It still only prints "Programmed by Tony"
and "Contents of set 1:" "Contents of set 2: " without the actual set data?

Why can't I decrease for all elements in my ArrayList/LinkedList

Original question :
Originally, I want to decrease (1) for all elements in MyLinkedList. But, since I cannot use foreach loop in MyLinkedList I first transferred all elements in MyLinkedList to ArrayList then with a foreach loop decreased (1) for all of the elements. But the thing is, I want to do this decrease operation per second.
input : 5-6-7
output : 1 second : 4-5-6
2 second : 3-4-5 ...
My problem :
The problem with my code is : it decreases (1) per second for the ith element of ArrayList.
input : 5-6-7
output : 1 second 4-6-7
2 second 4-5-6
...
Here's my code so far.
public void decreaseTime(MyLinkedList l1,MyLinkedList l2) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Node tmp = l1.first;
/*originally i want to decrease 1 for all elements of mylinkedlist.
since i cannot
use foreach in mylinkedlist i first transferred
elements of mylinkedlist to an Arraylist arr.
then decreased 1 for each element.*/
//lltoarr does copy all mylinkedlist elements to ArrayList arr.
lltoarr(l1, arr);
while (tmp != null) {
// simple sleep method which pauses the program for 1 second.
sleep();
int j = 0;
//decrease operation for each element of arr
for (int t : arr) {
//this is a trick for my program to work. you may ignore the next line.
int c = tmp.data.length() - 1;
t--;
arr.set(j, t);
// timeNew gets the new time which is the edited t element
int timeNew = arr.get(j);
if (somethin) {
//copy timeNew to String. i must store the time as string in mylinkedlist.
String newData = tmp.data.substring(0, c - 2) + timeNew
+ "h";
tmp.data = newData;
System.out.println(tmp.data);
sleep();
tmp = tmp.next;
}
else {
String newData = tmp.data.substring(0, c - 1) + timeNew
+ "h";
tmp.data = newData;
System.out.println(tmp.data);
sleep();
tmp = tmp.next;
}
j++;
}
System.out.println(arr);
}
}
MyLinkedList class :
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
public class MyLinkedList {
Node first, last;
public void insertFirst(String s) {
Node n = new Node(s);
if (first == null) {
last = n;
}
n.next = first;
first = n;
}
public void insertLast(String s) {
Node n = new Node(s);
if (first == null) {
first = n;
} else {
last.next = n;
}
last = n;
}
public void deleteFirst() {
if (first.next == null) {
first = null;
last = null;
}
else if (first == null)
return;
else
first = first.next;
}
public void lltoarr(MyLinkedList ll, ArrayList<Integer> arr) {
Node tmp = ll.first;
while (tmp != null) {
String numberOnly = tmp.data.replaceAll("[^0-9]", "");
int time = Integer.parseInt(numberOnly);
arr.add(time);
tmp = tmp.next;
}
}
//decreaseTime method here
public void sleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public void print() {
Node tmp = first;
int i = 0;
while (tmp != null) {
System.out.print(tmp.data + " - ");
tmp = tmp.next;
}
}
public int nOfNodes() {
int n = 0;
Node tmp = first;
while (tmp != null) {
tmp = tmp.next;
n++;
}
return n;
}
public Node search(String s) {
Node tmp = first;
while (tmp != null) {
if (tmp.data == s) {
return tmp;
} else {
tmp = tmp.next;
}
}
return null;
}
public void llCopy(MyLinkedList ll, MyLinkedList llcopy,int i) {
llcopy.insertLast(ll.nthNode(i));
}
public void insertAfter(String s, Node n) {
Node nn = new Node(s);
nn.next = n.next;
n.next = nn;
}
}
How you are indexing the list is not going to work.
If you want to iterate through the list and adjust each value I would suggest wrapping the Integer value with a holder that has a decrement function
e.g.
public IntegerHolder {
private int value;
....
public void decrement(){
this.value--;
}
}
Then you can do this
for(IntegerHolder value : list){
value.decrement();
}
Otherwise you could use a ListIterator and remove the old value and insert the decremented value,
for(ListIterator<Integer> iter = list.listIterator();iter.hasNext();){
int value = iter.next(); // get current value
iter.remove(); // remove it from list
iter.add(value-1); // insert decremented value where old value was
}
Personally I find the foreach loop for collections to be of limited value. Usually I want to access the iterator for some reason and it wont let me.

Sorting a List alphabetically using compareTo() method

I am writing a phonebook program in java and i need to list people in the list alphabetically and to do that i need to write a sorting algorithm for a list in java and it should use only compareTo() method. So can anyone help me to do that?
public void listAlpha()
{
Node tempNode = head;
for(int i = 0; i <= size; i++)
{
for(int j = 0; j <= i; j++)
{
int comparison = ((tempNode.getNext().getElement().getName()).compareTo(tempNode.getElement().getName()));
if(comparison < 0)
{
Person tempPerson = tempNode.getElement();
tempNode.setElement(tempNode.getNext().getElement());
tempNode.getNext().setElement(tempPerson);
tempNode = tempNode.getNext();
}
}
}
(By the way this is a homework and i am using my own data structures.)
This is the class that method i wrote above belongs:
import java.util.*;
/** Singly linked list implementation .*/
public class SLinkedList<E> implements LinkedList<E>, Iterable<E> {
protected Node<E> head; // head node of the list
protected Node<E> tail; // tail node of the list
protected int size; // number of nodes in the list
public Iterator<E> iterator()
{
return new LinkedListIterator(head);
}
/** Default constructor that creates an empty list */
public SLinkedList() {
head = null;
tail = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst(E newElement) {
Node<E> newNode = new Node(newElement,null);
if(size == 0) //if list is empty
tail = newNode;
newNode.setNext(head);
head = newNode;
size++;
}
public void addLast(E newElement) {
Node<E> newNode = new Node(newElement,null);
if(size == 0) //if list is empty
head = newNode;
if (size != 0) //if list is not empty
tail.setNext(newNode);
tail = newNode;
size++;
}
public E removeFirst() {
Node<E> tempNode = null;
if (size != 0) {
if(size == 1)
tail = null;
tempNode = head;
head = head.getNext();
tempNode.setNext(null);
size--;
}
//if list is empty then return null
return tempNode.getElement();
}
public E removeLast() {
Node<E> tempNode = head;
if(size == 0)
return null;
if(size == 1) {
head = null;
tail = null;
size--;
return tempNode.getElement();
}
//size is greater than 1
for(int i=1; i<=size-2; i++) {
tempNode = tempNode.getNext(); //go to element that before the tail
}
Node<E> tempNode2 = tail;
tail = tempNode;
tail.setNext(null);
size--;
return tempNode2.getElement();
}
public void remove(E element){
int index = 0;
boolean found = false;
Node<E> temp = head;
for(int i=1; i<=size; i++) {//find the node with element
index++;
if(temp.getElement().equals(element)){
found = true;
break;
}
temp = temp.getNext();
}
if(found){
if(index == 1)
removeFirst();
else if(index == size)
removeLast();
else{
//find the previous node
Node<E> prev = head;
for(int i=1; i<index-1; i++) {
prev = prev.getNext();
}
prev.setNext(temp.getNext());
temp.setNext(null);
size--;
}
}
}
public int searchList(E searchKey) {
if(size == 0)
return -1;
Node tempNode = head;
for(int i=1; i<=size; i++) {
if(tempNode.getElement().equals(searchKey))
return i; //return index of the node
tempNode = tempNode.getNext();
}
return -1; //not found
}
public void printList() {
Node tempNode = head;
for(int i=1; i<=size; i++) {
System.out.print(tempNode.getElement());
if(i!=size) //if it is not last element
System.out.print(" - ");
tempNode = tempNode.getNext();
}
System.out.println();
}
Person class:
public class Person
{
private String name;
private String surname;
private String address;
private PhoneNumber phone1;
private PhoneNumber phone2;
private PhoneNumber phone3;
public Person()
{
name = null;
surname = null;
address = null;
phone1.setPhone(0);
phone1.setType("");
phone2.setPhone(0);
phone2.setType("");
phone3.setPhone(0);
phone3.setType("");
}
public Person(String n, String s, String a,PhoneNumber p1, PhoneNumber p2, PhoneNumber p3)
{
name = n;
surname = s;
address = a;
phone1 = p1;
phone2 = p2;
phone3 = p3;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String getSur()
{
return surname;
}
public void setSur(String s)
{
surname = s;
}
public void insertPhone(PhoneNumber phone)
{
if(phone2 == null)
phone2 = phone;
else if(phone3 == null)
phone3 = phone;
}
public PhoneNumber getPhone1()
{
return phone1;
}
public PhoneNumber getPhone2()
{
return phone2;
}
public PhoneNumber getPhone3()
{
return phone3;
}
public String getAdd()
{
return address;
}
public void setAdd(String a)
{
address = a;
}
You can make your Person class implement Comparable, and define the following method:
public class Person implements Comparable<Person> {
// Your previous code
public int compareTo(Person other) {
if (other == null) {
// throw exception for example
}
return this.name.toLowerCase().compareTo(other.name.toLowerCase());
}
}
As everyone else has mentioned, compareTo is part of the Comparable interface.
How you implement it depends on whether you want to order by surname or name first and if you want them sorted ascending order.
For example, if you want to order by surname first, in ascending order:
public class Person implements Comparable<Person> {
// the parts of Person you already have would go here
public int compareTo(Person person) {
if (person == null) {
return -1;
}
if (surname != null && person.getSur() == null) {
return -1;
} else if (surname == null && person.getSur() != null) {
return 1;
} else if (surname != null && person.getSur() != null) {
int compare = surname.compareToIgnoreCase(person.getSur());
if (compare != 0) {
return compare;
}
}
// Note that we did nothing if both surnames were null or equal
if (name == null && person.getName() == null) {
return 0;
} else if (name != null && person.getName() == null) {
return -1;
} else if (name == null && person.getName() != null) {
return 1;
} else {
return name.compareToIgnoreCase(person.getName());
}
}
}
(I didn't actually test this code)
This relies on String's implementation of compareToIgnoreCase.
Note that this also moves all null objects and objects with null names and surnames to the end of the list.
Having said all that, if you implement Comparable, you can make the Collections API do the work for you using sort.
If you find that you need multiple different sort methods for an object, you can create a set of Comparator objects to do the sorting instead.
The Person class' signature should be like this:
public class Person implements Comparable<Person>
Add compareTo-method to Person class and use Collections.sort(personList) as starf suggested.
Implement Comparable in your Person class.
Your compareTo() method would then be something like:
public int compareTo(Person other) {
return name.compareTo(other.getName())
}
Then use Collections.sort(<your list of Person>);

Wants to get an element from 1st to last. But returns last to 1st

In get method, I want to get the element from first element to last. But it returns the list in reversed order (last to first element). How can I solve that problem with this code ?
import java.util.*;
class List {
Customer listPtr;
int index;
public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}
public Customer get(int index) {
Customer temp = listPtr;
int size = size();
if (index == 0) {
return listPtr;
} else {
while (size != index) {
size--;
temp = temp.next;
System.out.println(size + "------" + index);
}
return temp;
}
}
public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
temp = temp.next;
size++;
}
return size;
}
public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class DemoList {
public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "A");
Customer c2 = new Customer("10012", "B");
Customer c3 = new Customer("10013", "C");
Customer c4 = new Customer("10014", "D");
Customer c5 = new Customer("10015", "E");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
System.out.println(list.get(1));
//list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " : " + name;
}
public boolean equals(Object ob) {
Customer c = (Customer) ob;
return this.id.equals(c.id);
}
}
the question is somewhat ambiguous.
it looks like you're asking why .get() isn't returning the expected element?
while (size != index) {
size--;
temp = temp.next;
System.out.println(size + "------" + index);
}
return temp;
appears to be the culprit. your loop counter is decrementing from size() to desired index
while your reference is moving forward through the list.
This means that the value of size bears no real resemblance to what index you're looking at.
I'd use
int i =0;
while(++i <= index && i < size){
temp = temp.next;
}
if (i == index) {
return temp
} else {
//off the end, so throw exception
}
Since this is an assignment, it is not appropriate (or in your interest in the long-term) to give you a solution ...
The basic problem is that your get(i) method is not returning the value a position i.
That should be enough of a Hint to allow you to figure out what it is really doing ... and hence to fix it.
Looks like you are doing something very simple in a very complicated way.
I suggest:
First, remove the 'next' field from Customer.
Then, don't bother writing your own List class. Java has several perfectly good List implementations.
Example:
import java.util.*;
class DemoList {
public static void main(String args[]) {
List<Customer> list = new ArrayList<Customer>();
Customer c1 = new Customer("10011", "A");
Customer c2 = new Customer("10012", "B");
Customer c3 = new Customer("10013", "C");
Customer c4 = new Customer("10014", "D");
Customer c5 = new Customer("10015", "E");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
//first customer:
System.out.println(list.get(0)); //zero-based
//all customers:
for (Customer c : list) {
System.out.println(c);
}
}
}

Categories