Is the statement list.contains("are") (have commented it) being checked by matching character to character ?
import java.util.*;
class Tester {
public static void main(String args[]) {
String arr[] = {"how","are","you","veena"};
LinkedList<String> list = new LinkedList<String>();
for(String s : arr) {
list.add(s);
}
if(list.contains("are")) { // STATEMENT
System.out.println("Found !");
}
}
}
In this program if statement works. How does the contain method work ?
That method iterates over the linked list, and compare each element with the element passed by invoking equals() method. In this case, it will invoke String#equals(Object) method.
this is implementations of method contains and indexOf from LinkedList
public boolean contains(Object o) {
return indexOf(o) != -1;
}
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
so as you see it is iterating trough array till it finds first matching element
Related
For this method I needed to implement a custom made Stack class to see if the given string is a palindrome.
This is the custom Stack class:
public class Stack<T> {
private ArrayList<T> arrayList = new ArrayList<>();
private T head;
public Stack() {
arrayList.add(head);
}
#Override
public String toString() {
return arrayList.toString();
}
public boolean empty() {
return arrayList.size() == 1 ? true : false;
}
public T push(T element) {
arrayList.add(element);
head = element;
return element;
}
public T pop() {
T returnVal = arrayList.get(arrayList.size()-1);
if (!empty()) {
arrayList.remove(returnVal);
head = arrayList.get(arrayList.size()-1);
}
return returnVal;
}
public T peek() {
return head;
}
}
And this is the palindrome method:
public static boolean isPalindrome(String string) {
var stack = new Stack<Character>();
var flag = true;
for (int i=0; i<string.length(); i++)
stack.push(string.charAt(i));
if (string.charAt(0) == stack.peek()) {
for (int j=0; j<string.length(); j++) {
System.out.println(string.charAt(j) + " " + stack.peek());
if (string.charAt(j) != stack.pop()) {
flag = false;
break;
}
}
}
else
return false;
return flag;
}
When I run the method, it runs the loop only 2 times. The Stack object doesn't seem to pop. But when I tested the pop() method in the main method with just a set of different characters, it seemed to work. But in this isPalindrome() method, it doesn't seem to me that it works. Can someone please help out?
In your Stack.pop() method, the line arrayList.remove(returnVal); is not what you want.
It will remove the first occurrence of returnVal from the stack, but in pop() you need to remove the last occurrence of returnVal.
In Stack.pop() you need to remove the last element - which means you need to write
arrayList.remove(arrayList.size()-1);
Your complete Stack.pop() method would then be:
public T pop() {
T returnVal = arrayList.get(arrayList.size()-1);
if (!empty()) {
arrayList.remove(arrayList.size()-1);
head = arrayList.get(arrayList.size()-1);
}
return returnVal;
}
I implemented both add() and remove() methods from my ArrayList Class.
public void add(Object obj) {
if(data.length - currentSize <= 5) {
increaseListSize();
}
data[currentSize++] = obj;
}
public Object remove(int index){
if(index < currentSize){
Object obj = data[index];
data[index] = null;
int tmp = index;
while(tmp < currentSize){
data[tmp] = data[tmp+1];
data[tmp+1] = null;
tmp++;
}
currentSize--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
However, I don't know how to remove the specific index of my ArrayList of members.
if(temp[0].equals("ADD")) {
memberList.add(member);
fileOut.writeLine(member.toString());
fileLog.writeLine("New member " + member.toString() + " was succesfully added");
}
**else if(temp[0].equals("REMOVE")) {
//memberList.remove(index)
}**
}
Is there any suggestion of how should I get to remove the index of an object of the memberList? Can I modify my remove() method so that I could directly remove the object instead?
One possibility is to overload the existing remove-method with one that takes an Object-parameter. In the method body you have to iterate through the objects of the list and determine the index of the passed object. Then the existing remove-method is called using the previously determined index to remove the corresponding object.
The following implementation removes the first occurrence of the specified object from the list. The removed object is returned. If the list does not contain the object null is returned.
public Object remove(Object obj){
int index = -1;
for (int i = 0; i < data.length; i++) {
if (data[i] == obj) {
index = i;
break;
}
}
if (index != -1) {
return remove(index);
}
return null;
}
My linked list is printing blank. Can someone explain what I am missing here.
class Linklist {
private Linklist first;
public int items;
public int itemLocation;
public int lastIndex = -1;
private final String[] list;
public Linklist nextlink;
//Link constructor
public Linklist(int totalItems) {
items = 0;
list = new String[totalItems];
}
public Linklist getNext()
{
return this.nextlink;
}
public void setNext(Linklist n)
{
nextlink = n;
}
public void insert (String item){
list[items] = item;
items++;
}
public void delete(String item){
int location = 0;
while(item.compareTo(list[location]) != 0)
location++;
list[location] = list[items -1];
items--;
}
public boolean doesExist (String item){
boolean search;
int location = 0;
boolean found = false;
search = (location < items);
while (search && !found)
{
if (item.compareTo(list[location])==0)
found = true;
else
{
location++;
search = (location<items);
}
}
return found;
}
public void printUnsortedlist(){
System.out.print("{" + list + "} ");
}
public void printList(){
Linklist currentLink = first;
System.out.print("List: ");
while(currentLink != null){
currentLink.printUnsortedlist();
currentLink = currentLink.getNext();
}
System.out.println("");
}
}
public class Unsortedlist{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Linklist list = new Linklist(9);
list.insert("Sun");
list.insert("Mercury");
list.insert("Venus");
list.insert("Earth");
list.insert("Mars");
list.insert("Jupiter");
list.insert("Neptune");
list.insert("Saturn");
list.insert("Uranus");
list.printList();
list.delete("Sun");
if(list.doesExist("Earth"))
System.out.println("Earth is in the list");
else
System.out.println("Earth does not exist!");
list.printList();
}
}
This is my output:
List:
Earth is in the list
List:
BUILD SUCCESSFUL (total time: 0 seconds)
When I integrate a size() method for example:
public int size(){
int currentSize = 0;
Linklist current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
I get this as the output:
{8} Earth is in the list
My linked list is there but can not figure out why it is printing blank.
For your code ,a few places make me more confused.
First,Why you already have a field "list" ,but then you also set a pointer to the nextlink,if you just want to print as a list ,you could only set two field String value and Linklist next,then you can print your list .
Second,I think the reason why your list is blank is that you set first to currentLink ,and first is null all the time.To solve this problem ,maybe you can change first to this,then your while code will run as you like it.
Just like this:
public void printList(){
Linklist currentLink = this;
System.out.print("List: ");
while(currentLink != null){
currentLink.printUnsortedlist();
currentLink = currentLink.getNext();
}
System.out.println("");
}
But still ,you need to improve your code at many places is you really want the code do a perfect job.Hope this help you out.
Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)
in all honesty, I've spent a few days looking at this and trying to figure it out, but have come up very short. The goal is to see if a trie node has a next, if so what it is.
Where it's called by:
public Iterator<String> iterator() {
return new TrieIterator();
}
calls this to implement my own iterator. I've tried using a position in the array + 1 for the hasNext(), also comparing things to size, and number or nodes, and children, and have come up short. My most recent try was something along the lines of (below) but doesn't work.
hasNext() {
return this.children.hasChildren(); /* doesn't work */
}
public class TrieIterator implements Iterator<String> {
public TrieIterator(){
}
public boolean hasNext() {
return false;
}
public String next() {
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
here's the trieNode class as well:
public class TrieNode {
protected char letter = ' ';
protected TrieNode parentNode = null;
protected boolean fullWord = false;
protected TrieNode[] children = new TrieNode[26];
protected int prefixes = 0;
public TrieNode(char letter, TrieNode parentNode){
this.letter = letter;
this.parentNode = parentNode;
}
public boolean hasChildren(){
int index = 0;
while(index < children.length){
if(children[index] != null) {
return true;
}
index++;
}
return false;
}
public TrieNode nodeForLetter(char ch) {
return children[ch - 97];
}
public boolean isEndOfWord() {
return letter == '*';
}
}
and adding and deleting is as follows:
public void addWord(String s) {
if (hasWord(s)) return;
int index = 0;
TrieNode current = root;
char[] letters = s.toCharArray();
while(index < s.length()){
TrieNode child = current.children[letters[index] - 97];
if(child == null){
child = new TrieNode(letters[index], current);
child.prefixes++;
numOfNodes++;
}
current = child;
index++;
if(index == s.length()){
current.fullWord = true;
numOfWords++;
}
}
}
public void deleteWord(String s) {
if(s.length() == 0) return;
if(size() == 0) return;
if(!hasWord(s)) return;
TrieNode current = root;
for (char ch : s.toCharArray()) {
TrieNode child = current.children[s.charAt(ch) - 97];
if(child.prefixes == 1){
child = null;
return;
}
else{
child.prefixes--;
current = child;
}
}
current.fullWord = false;
}
public boolean hasWord(String s) {
if(size() == 0) return false;
char[] letters = s.toCharArray();
int l = letters.length;
TrieNode current = root;
int i;
for (i = 0; i < l; i++){
if (current == null) return false;
current = current.children[letters[i] - 97];
}
if (i == l && current == null) return false;
if (current != null && !current.fullWord) return false;
return true;
}
Please don't change current implementation of the trie :)
Your attempt at implementing hasNext() with this.children.hasChildren(); won't work because children is an array of TrieNode, so it doesn't have any hasChildren() method.
The hasChildren() method is a method of TrieNode, not its children array.
You need to keep track of the current node, the position in the current node, and all the characters seen so far. hasNext() should return true if there are any more words, which means if the node is a full word or if it has any children that haven't been visited yet that are full words. (But, I assume the leaf nodes are always full words, so the latter test can simply be if the node has any children that haven't been visited yet.)
You will need to decide if you will return shorter words before longer ones (do you return a word from next() as soon as you arrive at a full word node, or only after visiting its children?) You will also need to maintain a stack of nodes, so that after you have descended to a child node, you can return to your previous position in the parent node.
It isn't a trivial task. I would suggest starting with a Trie built from a very small set of words (like "a", "an", and "at"), and getting that fully debugged before you move on to three letter words or more.
(You should also consider what you intend to do if the Trie is modified while you're iterating through it. The standard java.util classes update a counter on every modification, and test that it hasn't changed in the iterator. If it has, they throw a ConcurrentModificationException. Iterators using this strategy are called fail-fast iterators.)