Question

Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...

Data Structures - Singly Linked Lists

You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list.

package linkedlists;
public class SinglyLinkedList<E> implements Cloneable {
   // ---------------- nested Node class ----------------
   /**
   * Node of a singly linked list, which stores a reference to its element and to
   * the subsequent node in the list (or null if this is the last node).
   */
   private static class Node<E> {

       /** The element stored at this node */
       private E element; // reference to the element stored at this node

       /** A reference to the subsequent node in the list */
       private Node<E> next; // reference to the subsequent node in the list

       /**
       * Creates a node with the given element and next node.
       *
       * @param e the element to be stored
       * @param n reference to a node that should follow the new node
       */
       public Node(E e, Node<E> n) {
           element = e;
           next = n;
       }

       // Accessor methods
       /**
       * Returns the element stored at the node.
       *
       * @return the element stored at the node
       */
       public E getElement() {
           return element;
       }

       /**
       * Returns the node that follows this one (or null if no such node).
       *
       * @return the following node
       */
       public Node<E> getNext() {
           return next;
       }

       // Modifier methods
       /**
       * Sets the node's next reference to point to Node n.
       *
       * @param n the node that should follow this one
       */
       public void setNext(Node<E> n) {
           next = n;
       }

   } // ----------- end of nested Node class -----------

   // instance variables of the SinglyLinkedList
   /** The head node of the list */
   private Node<E> head = null; // head node of the list (or null if empty)

   /** The last node of the list */
   private Node<E> tail = null; // last node of the list (or null if empty)

   /** Number of nodes in the list */
   private int size = 0; // number of nodes in the list

   /** Constructs an initially empty list. */
   public SinglyLinkedList() {
   } // constructs an initially empty list

   // access methods
   public int size() {
       return size;
   }
   public boolean isEmpty() {
       return size == 0;
   }
   public E first() { // returns (but does not remove) the first element
       if (isEmpty())
           return null;
       return head.getElement();
   }
   public E last() { // returns (but does not remove) the last element
       if (isEmpty())
           return null;
       return tail.getElement();
   }

   // update methods
   public void addFirst(E e) { // adds element e to the front of the list
       head = new Node<>(e, head); // create and link a new node
       if (size == 0)
           tail = head; // special case: new node becomes tail also
       size++;
   }


   public void addLast(E e) { // adds element e to the end of the list
       Node<E> newest = new Node<>(e, null); // node will eventually be the tail
       if (isEmpty())
           head = newest; // special case: previously empty list
       else
           tail.setNext(newest); // new node after existing tail
       tail = newest; // new node becomes the tail
       size++;
   }
   public E removeFirst() { // removes and returns the first element
       if (isEmpty())
           return null; // nothing to remove
       E answer = head.getElement();
       head = head.getNext(); // will become null if list had only one node
       size--;
       if (size == 0)
           tail = null; // special case as list is now empty
       return answer;
   }

   @SuppressWarnings({ "unchecked" })
   public boolean equals(Object o) {
       if (o == null)
           return false;
       if (getClass() != o.getClass())
           return false;
       SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
       if (size != other.size)
           return false;
       Node walkA = head; // traverse the primary list
       Node walkB = other.head; // traverse the secondary list
       while (walkA != null) {
           if (!walkA.getElement().equals(walkB.getElement()))
               return false; // mismatch
           walkA = walkA.getNext();
           walkB = walkB.getNext();
       }
       return true; // if we reach this, everything matched successfully
   }

   @SuppressWarnings({ "unchecked" })
   public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
       // always use inherited Object.clone() to create the initial copy
       SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
       System.out.println(other.head.getElement());

       if (size > 0) { // we need independent chain of nodes
           other.head = new Node<>(head.getElement(), null);
           Node<E> walk = head.getNext(); // walk through remainder of original list
           Node<E> otherTail = other.head; // remember most recently created node
           while (walk != null) { // make a new node storing same element
               Node<E> newest = new Node<>(walk.getElement(), null);
               otherTail.setNext(newest); // link previous node to this one
               otherTail = newest;
               walk = walk.getNext();
           }
       }

       return other;
   }

   public int hashCode() {
       int h = 0;
       for (Node walk = head; walk != null; walk = walk.getNext()) {
           h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
           h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
       }
       return h;
   }
   public String toString() {
       StringBuilder sb = new StringBuilder("(");
       Node<E> walk = head;
       while (walk != null) {
           sb.append(walk.getElement());
           if (walk != tail)
               sb.append(", ");
           walk = walk.getNext();
       }
       sb.append(")");
       return sb.toString();
   }

      public void reverse() {
       Node<E> reversedPart = null;
       Node<E> curr = head;
       tail = curr;
       while (curr != null) {
           Node<E> next = curr.next;
           curr.next = reversedPart;
           reversedPart = curr;
           curr = next;

       }
       head = reversedPart;
   }
  // main method
   public static void main(String[] args) {

       SinglyLinkedList<String> list = new SinglyLinkedList<String>();
       list.addFirst("MSP");
       list.addLast("ATL");
       list.addLast("BOS");
       //
       list.addFirst("LAX");

       System.out.println("Original List: "+list);

       //
       list.reverse();
       System.out.println("Reversed List: "+list);
      


       System.out.println("Swaped List: "+list);

   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// ---------------- nested Node class ----------------
   /**
   * Node of a singly linked list, which stores a reference to its element and to
   * the subsequent node in the list (or null if this is the last node).
   */
   private static class Node<E> {

       /** The element stored at this node */
       private E element; // reference to the element stored at this node

       /** A reference to the subsequent node in the list */
       private Node<E> next; // reference to the subsequent node in the list

       /**
       * Creates a node with the given element and next node.
       *
       * @param e the element to be stored
       * @param n reference to a node that should follow the new node
       */
       public Node(E e, Node<E> n) {
           element = e;
           next = n;
       }

       // Accessor methods
       /**
       * Returns the element stored at the node.
       *
       * @return the element stored at the node
       */
       public E getElement() {
           return element;
       }

       /**
       * Returns the node that follows this one (or null if no such node).
       *
       * @return the following node
       */
       public Node<E> getNext() {
           return next;
       }

       // Modifier methods
       /**
       * Sets the node's next reference to point to Node n.
       *
       * @param n the node that should follow this one
       */
       public void setNext(Node<E> n) {
           next = n;
       }

   } // ----------- end of nested Node class -----------

   // instance variables of the SinglyLinkedList
   /** The head node of the list */
   private Node<E> head = null; // head node of the list (or null if empty)

   /** The last node of the list */
   private Node<E> tail = null; // last node of the list (or null if empty)

   /** Number of nodes in the list */
   private int size = 0; // number of nodes in the list

   /** Constructs an initially empty list. */
   public SinglyLinkedList() {
   } // constructs an initially empty list

   // access methods
   public int size() {
       return size;
   }
   public boolean isEmpty() {
       return size == 0;
   }
   public E first() { // returns (but does not remove) the first element
       if (isEmpty())
           return null;
       return head.getElement();
   }
   public E last() { // returns (but does not remove) the last element
       if (isEmpty())
           return null;
       return tail.getElement();
   }

   // update methods
   public void addFirst(E e) { // adds element e to the front of the list
       head = new Node<>(e, head); // create and link a new node
       if (size == 0)
           tail = head; // special case: new node becomes tail also
       size++;
   }


   public void addLast(E e) { // adds element e to the end of the list
       Node<E> newest = new Node<>(e, null); // node will eventually be the tail
       if (isEmpty())
           head = newest; // special case: previously empty list
       else
           tail.setNext(newest); // new node after existing tail
       tail = newest; // new node becomes the tail
       size++;
   }
   public E removeFirst() { // removes and returns the first element
       if (isEmpty())
           return null; // nothing to remove
       E answer = head.getElement();
       head = head.getNext(); // will become null if list had only one node
       size--;
       if (size == 0)
           tail = null; // special case as list is now empty
       return answer;
   }

   @SuppressWarnings({ "unchecked" })
   public boolean equals(Object o) {
       if (o == null)
           return false;
       if (getClass() != o.getClass())
           return false;
       SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
       if (size != other.size)
           return false;
       Node walkA = head; // traverse the primary list
       Node walkB = other.head; // traverse the secondary list
       while (walkA != null) {
           if (!walkA.getElement().equals(walkB.getElement()))
               return false; // mismatch
           walkA = walkA.getNext();
           walkB = walkB.getNext();
       }
       return true; // if we reach this, everything matched successfully
   }

   @SuppressWarnings({ "unchecked" })
   public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
       // always use inherited Object.clone() to create the initial copy
       SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
       System.out.println(other.head.getElement());

       if (size > 0) { // we need independent chain of nodes
           other.head = new Node<>(head.getElement(), null);
           Node<E> walk = head.getNext(); // walk through remainder of original list
           Node<E> otherTail = other.head; // remember most recently created node
           while (walk != null) { // make a new node storing same element
               Node<E> newest = new Node<>(walk.getElement(), null);
               otherTail.setNext(newest); // link previous node to this one
               otherTail = newest;
               walk = walk.getNext();
           }
       }

       return other;
   }

   public int hashCode() {
       int h = 0;
       for (Node walk = head; walk != null; walk = walk.getNext()) {
           h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
           h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
       }
       return h;
   }
   public String toString() {
       StringBuilder sb = new StringBuilder("(");
       Node<E> walk = head;
       while (walk != null) {
           sb.append(walk.getElement());
           if (walk != tail)
               sb.append(", ");
           walk = walk.getNext();
       }
       sb.append(")");
       return sb.toString();
   }

      public void reverse() {
       Node<E> reversedPart = null;
       Node<E> curr = head;
       tail = curr;
       while (curr != null) {
           Node<E> next = curr.next;
           curr.next = reversedPart;
           reversedPart = curr;
           curr = next;

       }
       head = reversedPart;
   }
  // main method
   public static void main(String[] args) {

       SinglyLinkedList<String> list = new SinglyLinkedList<String>();
       list.addFirst("MSP");
       list.addLast("ATL");
       list.addLast("BOS");
       //
       list.addFirst("LAX");

       System.out.println("Original List: "+list);

       //
       list.reverse();
       System.out.println("Reversed List: "+list);
      


       System.out.println("Swaped List: "+list);

   }
}

Add a comment
Know the answer?
Add Answer to:
Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Question: SWAPPING NODES IN A SINGULARLY LINKED LIST: I am attempting to create a program that...

    Question: SWAPPING NODES IN A SINGULARLY LINKED LIST: I am attempting to create a program that swaps 2 nodes (no matter where they are in the list) and am having some difficulty. I can't seem to figure out why this swap method is throwing an error. Code: (SWAPPING METHOD AND TEST LINE BOLDED) package linkedlists; public class SinglyLinkedList<E> implements Cloneable { //---------------- nested Node class ---------------- /** * Node of a singly linked list, which stores a reference to its...

  • Write a method with signature "concatenate(LinkedQueue<E> Q2)" for the LinkedQueue<E> class that takes all elements of...

    Write a method with signature "concatenate(LinkedQueue<E> Q2)" for the LinkedQueue<E> class that takes all elements of Q2 and appends them to the end of the original queue. The operation should run in O(1) time and should result in Q2 being an empty queue. Write the necessary code to test the method.You may just modify the SinglyLinkedList class to add necessary support. LinkedQueue Class public class LinkedQueue<E> implements Queue<E> { /** The primary storage for elements of the queue */ private...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • Q1: You can find a file that defines the CircularlyLinked List class similar to what we...

    Q1: You can find a file that defines the CircularlyLinked List class similar to what we discussed in the class. Download the file and work on it. Your task is to: 1. Complete the missing methods in the file as discussed in the class. Search for the comment/" MISSING / in the file to see the methods that need to be completed. 2. Add the following methods to the class a. public Node getMin 1. Task: find the node with...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • (1) Implement the countKey(T element) method, which should return a count of the number of times...

    (1) Implement the countKey(T element) method, which should return a count of the number of times that the given key (the element) is found in the list. (2) Implement the indexOf(T element) method, which is similar as the indexOf method in the String class. It returns the index (the position starting from the head node) of the first occurrence of the given element, or -1, if the element does not occur in the list. You will need to track the...

  • C++: I need implement this code using Double Linked List using the cosiderations 1. head point...

    C++: I need implement this code using Double Linked List using the cosiderations 1. head point to null in an empty list 2. There is not need of a tail pointer /*This class implements the singly linked list using templates Each list has two attributes:    -head: first node in the list    -tail: last node in the list #include "circDLLNode.h" template class { public:    //Default constructor: creates an empty list    ();    //Destructor: deallocate memory    ~();  ...

  • Write a Client class with a main method that tests the data structures as follows: For...

    Write a Client class with a main method that tests the data structures as follows: For the ArrayStack, LinkedStack, ArrayQueue and LinkedQueue: Perform a timing test for each of these data structures. Each timing test should measure in nanoseconds how long it takes to add N Integers to the structure and how long it takes to remove N Integers from the structure. N should vary from 10 to 100,000,000 increasing N by a factor of 10 for each test. Depending...

  • Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(),...

    Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 {    private Node head, tail; private int size;    public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT