Java Program find below the previous code public class LinkList { IntegerNode he
ID: 3764868 • Letter: J
Question
Java Program
find below the previous code
public class LinkList
{
IntegerNode head; // Header Delcaration
public void insert(int pos, IntegerNode item) //add one node there
{
IntegerNode dummy = new IntegerNode(-1, null); // dummy node will assist in setting the link
dummy.next = head;
IntegerNode curr = dummy;
while(--pos >= 0) // find the position, curr.next will be right position to add new node there
{
curr = curr.next;
}
item.next = curr.next; //insert the node from current to next
curr.next = item;
head = dummy.next; // update head
}
public IntegerNode get(int pos) //get int pos
{
IntegerNode gets = head;
if(pos+1 == 0)
{
return gets;
}
for(int i=0;i<pos+1;i++) //updating the link by 1
{
gets = gets.next;
}
return gets;
}
public void remove(int value)
{
IntegerNode l1 = head; //create two other references that will used as instruction
IntegerNode l2 = head.next;
while(l2!=null) //check if the l2 is equal to value until the l2 reaches end
{
if(l2.item==value)
{
l1.next = l2.next;
l2.next = null;
}
l2 = l2.next; //updating references by one element
l1 = l1.next;
}
}
public String toString() //return the string representation of the list
{
StringBuilder ret = new StringBuilder();
IntegerNode curr = head;
while (curr != null)
{
if(curr != head)
{
ret.append("->");
}
ret.append(curr.item);
curr = curr.next;
}
return ret.toString();
}
public static void main(String[] args)
{
LinkList list = new LinkList();
list.insert(0,new IntegerNode(10));
list.insert(0,new IntegerNode(20));
IntegerNode s = list.get(1);
System.out.println("Item at index 1 is " + s );
list.insert(2,new IntegerNode(30));
System.out.println("Before removing: ");
System.out.println(list);
list.remove(10);
System.out.println("After removing: ");
System.out.println(list);
}
}
Explanation / Answer
Brief description of the algorithm: I used a stack. First I will traverse from left to right in the linked list and push item in that node into the stack. Then I traverse Linkedlist for the second time this time I will check top of the stack with the item in the curr node if it matches I move on or it is not a palindrome. If I reach the end with out a mismatch then it's a palindrome.
public bool checkPalindrome(){
Stack st = new Stack();
IntegerNode curr = head;
while (curr != null)
{
st.push(new Integer(curr.item));
curr = curr.next;
}
curr=head;
while(curr!=null)
{
if(st.peek()!=new Integer(curr).item){
return false;
}
}
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.