Question

In: Computer Science

Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and...

Data Structures on Java

Basic Linked List exercises

a. Suppose x is a linked-list node and not the last node on the list.

What is the effect of the following code fragment?

x.next = x.next.next

b. Singly Linked List has two private instance variables first and last as that point to the first and the last nodes in the list, respectively. Write a fragment of code that removes the last node in a linked list whose first node is first. Is there any advantage of keeping the last pointer in a linked list implementation? Explain.

Solutions

Expert Solution

Here are solutions to (a) and (b).

Along with the solutions, sample codes are added to demonstrate working of code fragments. Also, sample output is added at the end of each program.

(a):

Given that x is a linked-list node and not the last node on the list.

Given code fragment is:

x.next = x.next.next

After the above code fragment is executed, the 'next' field of x stores the address present in the 'next' field of the node that follows 'x'.

In other words,the node 'x' no longer points to the node that was previously present after 'x'. Instead , it points to the node that follows it.

For example, let us consider three nodes x,y and z in a linked list.

Before execution of the given statement:

x -> y -> z

After execution of the given statement:

x -> z

Hence, we can say that the given code fragment removes the node that follows 'x' from the linked list. (In case of above example, the node 'y' is removed from the linked list.)

Here is a sample program to demonstrate this.

Sample program:

import java.util.LinkedList;
import java.util.List;

public class SampleList {

    public static class Node{

        String data;
        Node next;

        Node(){

        }
        Node(String data){
            this.data=data;
            this.next=null;
        }
    }

    public static class LinkedListImp{

        Node head,tail;

        LinkedListImp(){
            head=null;
            tail=null;
        }

        void insert(String data){
            Node newNode=new Node(data);
            if(head==null){
                head=newNode;
                tail=newNode;
            }
            else{
                tail.next=newNode;
                tail=newNode;
            }
        }

        void display(){

            Node temp=head;
            while(temp!=null){
                System.out.print(temp.data+"  ");
                temp=temp.next;
            }
        }

        Node getHead(){
            return head;
        }
    }

    public static void main(String[] args){

        LinkedListImp linkedList=new LinkedListImp();



        linkedList.insert("X");
        linkedList.insert("Y");
        linkedList.insert("Z");

        Node x=linkedList.getHead();

        System.out.println("The elements in linked list before execution of code fragment are:");

        linkedList.display();

        x.next=x.next.next;

        System.out.println("\nThe elements in linked list before execution of code fragment are:");

        linkedList.display();
    }
}

Output:

(b):

Here is fragment of code that removes the last node of the linked list:

Code fragment:

        if(first==null){    /*checks if the linked list is empty*/
            System.out.println("Linked list is empty");
        }
        else if(first==last){     /*checks if there is only one node in the list*/
            first=null;
            last=null;
        }
        else{
            Node temp = first;   /*creates a temp node that points to first*/
            while(temp.next!=last){     /*this loop makes temp traverse the list until temp.next=last*/
                temp=temp.next;
            }
            temp.next=null;    /*makes temp.next point to null*/
            last=temp;      /*makes last point to temp*/
        }

Advantage of keeping last pointer in a linked list implementation:

last pointer of a linked list implementation makes the insertion of new node into linked list easier.This is because if we want to add new node into the linked list, we just have to make the last node's 'next' point to new node.

If there is no last pointer, everytime a new node needs to be inserted into the list, the list should be traversed from 'first' pointer until we reach the last node of the list and then make that node point to new node.

This is time consuming, especially when the list is long.

Hence, keeping a 'last' pointer is beneficial.

Here is the code to demonstrate removal of last node from linked list:

import java.util.LinkedList;
import java.util.List;

public class SampleList {

    public static class Node{

        String data;
        Node next;

        Node(){

        }
        Node(String data){
            this.data=data;
            this.next=null;
        }
    }

    public static class LinkedListImp{

        private Node first,last;

        LinkedListImp(){
            first=null;
            last=null;
        }

        void insert(String data){
            Node newNode=new Node(data);
            if(first==null){
                first=newNode;
                last=newNode;
            }
            else{
                last.next=newNode;
                last=newNode;
            }
        }

        void display(){

            Node temp=first;
            while(temp!=null){
                System.out.print(temp.data+"  ");
                temp=temp.next;
            }
        }

        Node getFirst(){
            return first;
        }

        Node getLast(){
            return last;
        }
    }

    public static void main(String[] args){

        LinkedListImp linkedList=new LinkedListImp();



        linkedList.insert("X");
        linkedList.insert("Y");
        linkedList.insert("Z");

        System.out.println("The elements in linked list before execution of code fragment are:");

        linkedList.display();


        Node first=linkedList.getFirst();
        Node last=linkedList.getLast();

        if(first==null){    /*checks if the linked list is empty*/
            System.out.println("Linked list is empty");
        }
        else if(first==last){     /*checks if there is only one node in the list*/
            first=null;
            last=null;
        }
        else{
            Node temp = first;   /*creates a temp node that points to first*/
            while(temp.next!=last){     /*this loop makes temp traverse the list until temp.next=last*/
                temp=temp.next;
            }
            temp.next=null;    /*makes temp.next point to null*/
            last=temp;      /*makes last point to temp*/
        }

        System.out.println("\nThe elements in linked list before execution of code fragment are:");

        linkedList.display();
    }
}

Output:


Related Solutions

Working on a c++ data structures assignment.   Linked List add node. I have the head case...
Working on a c++ data structures assignment.   Linked List add node. I have the head case and the tail case working but the middle/general case I can not get to work for the life of me. I have included the header file and the data struct file below   #ifndef LINKEDLIST_H #define LINKEDLIST_H #include "data.h" #include <iostream>   //take this out using std::cout; class LinkedList{     public:         LinkedList();         ~LinkedList();         bool addNode(int, string);         bool deleteNode(int);         bool getNode(int, Data*);         void printList(bool = false);         int getCount();         void...
Suppose a linked list of 20 nodes. The middle node has a data –250. Write the...
Suppose a linked list of 20 nodes. The middle node has a data –250. Write the pseudocode to replace the middle node of the linked list with a new node and new data. Assume that the list's head pointer is called head_ptr and the data for the new node is called entry
JAVA DATA STRUCTURE (Linked Lists/Queue) public class Node {    int value;    Node nextNode;   ...
JAVA DATA STRUCTURE (Linked Lists/Queue) public class Node {    int value;    Node nextNode;    Node(int v, Node n){        value = v;        nextNode = n;    }    Node (int v){        this(v,null);    } } public class Stack {    protected Node top;    Stack(){        top = null;    }    boolean isEmpty(){        return( top == null);    }    void push(int v){        Node tempPointer;       ...
Assume that a singly linked list is implemented with a header node, but no tail node,...
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a pointer to the header node. Write a class in C++ that includes methods to a. return the size of the linked list b. print the linked list c. test if a value x is contained in the linked list d. add a value x if it is not already contained in the linked list e. remove a value...
Assume that a singly linked list is implemented with a header node, but no tail node,...
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a pointer to the header node. Write a class that includes methods to a. return the size of the linked list b. print the linked list c. test if a value x is contained in the linked list d. add a value x if it is not already contained in the linked list e. remove a value x if...
What is a linked data structure? What is a node? What are the benefits of linked...
What is a linked data structure? What is a node? What are the benefits of linked structure? What are the drawbacks of linked structure? What are the differences between singly linked and doubly linked structures? Give examples of when a linked structure could be used.
I've provided a Node class that implements a node of a simple singly-linked list (with .value...
I've provided a Node class that implements a node of a simple singly-linked list (with .value and .next fields), and an empty LinkedList class. Your task is to implement LinkedList.sort(l), where given the node l as the head of a singly-linked list, LinkedList.sort(l) sorts the nodes in the list into ascending order according to the values in the .value field of each node. Your implementation should do an in-place update of the list. It is ok to use a simple...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int size; public CircularLinkedList() { tail= null; size = 0; } public int size(){ return size; } public boolean isEmpty() { return size==0; } //if list is not empty return the first element public E first() { if (isEmpty()) return null; //code here return 0; } //if list not empty return last element public E last() { if (isEmpty()) return null; return tail.getElement(); } /*...
IN JAVA Objectives Practice Link list, List node, compareTo, user defined data type, interfaces Movie List...
IN JAVA Objectives Practice Link list, List node, compareTo, user defined data type, interfaces Movie List Create a link list of the movies along with the rating, number of the people who watched the movie and the genre of the movie. Required classes Movie class ListNode class MovieList class List interface Driver class Movie class implements Comparable Attributes: movie’s name, genre, rating, number of people watched Methods: constructor, getter, setter, equals, compreTo, toString ListNode class Attributes: each node has two...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you will implement the functionality of a stack and a queue using a linked list. Your program must use of the declaration of the Stack and Queue class in Stack.h and Queue.h You have to implement the functionalities of queue (enq, deq, displayQueue) in a file called Queue.cpp. All the functions in Queue.cpp should follow the prototypes declared in Queue.h. Your code should make use...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT