How to write recursion get methods in doubly linkedlist? - java

here is my code
public class LinkedListDeque<T> implements Deque {
private Node sentinel;
private int size;
private static class Node<T> {
private T item;
private Node pre;
private Node next;
public Node(T i, Node p, Node n) {
item = i;
pre = p;
next = n;
}
public LinkedListDeque() {
size = 0;
sentinel = new Node(null, null, null);
sentinel.next = sentinel;
sentinel.pre = sentinel;
}
public LinkedListDeque(T item) {
size = 1;
Node first = new Node(item, sentinel, sentinel);
sentinel = new Node(null, first, first);
}
public Object getRecursive(int index) {}
}
I just can't figure out how to do it. I can do it in a interation way. I don't know where to start to build a recursion methods.

public Node getNode(Node n, int index, int pos) {
if (index == pos) {
return n;
}
if (index > pos || n == null) {
return null;
}
return getNode(n.next, index, pos++);
}
I believe this is what you want, and the initial call is with pos=0 and the head of the LinkedList.
I think you need to look up how recursion works though, because you failed to even attempt the problem.

Related

How to insert a node in specific index [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
First of all pardon me if the way I'm asking is wrong, I'm new at programming and still need a lot of learning, here is my code
This is my Node class
public class Node
{
int value;
Node link;
void setValue(int a){
value = a;
}
int getValue(){
return value;
}
void setNode(Node i){
link = i;
}
Node getNode(){
return link;
}
}
And this one my NodeContainer class
public class NodeContainer
{
Node tail;
Node head;
void setHead(int i){
Node a = new Node();
a.setValue(i);
head = a;
tail = head;
}
Node getHead(){
return head;
}
void addNode(int i){
Node a = new Node();
a.setValue(i);
tail.setNode(a);
tail = a;
}
void addNode(int i,int index){
Node a = new Node();
a.setValue(i);
int c = 1;
Node temp = head;
Node first = head;
while(head!=null){
head = head.getNode();
if(c==index-1){
a.setNode(head.getNode());
temp = head;
temp.setNode(a);
}
c++;
}
head = first;
head.setNode(temp);
}
int count(){
int c = 1;
boolean have = true;
if(head!=null){
while(head.getNode()!=null){
c++;
head = head.getNode();
}
return c;
}
else{
have = false;
return 0;}
}
}
i just cant think a way to insert a node in spesific index, i tried it on addNode method have tried so many ways i can think of but it cant work, thanks in advance
Comments:
You do not need to keep track of the tail (necessarily) I see you are new to linked lists, so perhaps try to master the basics before adding extra features.
Also, try adding some white space in your code, it makes it easier to read.
I heavily commented the section that covers inserting at a specified index. put all these files in the same folder, the compile it. You should get the output that follows:
Output:
0 1 2 3 4 5 6 7 8 9
inserting -1 at position 5
0 1 2 3 4 -1 5 6 7 8 9
Main class:
class test {
public static void main(String[] args) {
NodeContainer linkedList = new NodeContainer();
for (int i = 0; i < 10; i++) {
linkedList.addNode(i);
}
display(linkedList.head);
// NOTE - indexes start at 0, not 1
System.out.println("inserting -1 at position 5");
linkedList.addNode(-1, 5);
display(linkedList.head);
}
public static void display(Node node) {
while (node != null) {
System.out.print(node.value + " ");
node = node.link;
}
System.out.println();
}
}
Node Container class:
public class NodeContainer {
public Node head;
public int size;
public NodeContainer() {
size = 0;
head = null;
}
public void addNode(int i) {
Node node = new Node(i);
if (head == null) {
head = node;
} else {
Node temp;
temp = head;
while (temp.link != null) {
temp = temp.link;
}
temp.link = node;
}
size++;
}
public void addNode(int i, int index) {
Node node;
Node temp;
int count;
// If we want to insert
// into the front of the list
if (index == 0) {
// User a constructor instead of
// making a new node every time,
// then typing set value
node = new Node(i);
node.link = head;
head = node;
// If the index is within the linkedlist
} else if (index > 0 && index < size) {
count = 0;
temp = head;
// Keep looking until the index prior to
// the one we want to insert at
while(temp.link != null && count < size) {
// Once we find it, break out the loop
if (count == index-1) {
break;
}
// Keep traversing the list
temp = temp.link;
// increment counter
count++;
}
// Instantiate the node
node = new Node(i);
// Point this node's link to
// the n-1th node's link
node.link = temp.link;
// Set n-1th node's next to this
// node (effectively putting it
// in position n)
temp.link = node;
// Otherwise don't do anything
} else {
;
}
}
}
Node class:
public class Node {
public int value;
public Node link;
// User a constructor
public Node(int i) {
value = i;
link = null;
}
public void setValue(int a) {
value = a;
}
public int getValue() {
return value;
}
public void setNode(Node i) {
link = i;
}
public Node getNode() {
return link;
}
}
I have updated your original code snippet to be like this :
public class Node
{
int value;
Node next;
void setValue(int value){
this.value = value;
}
int getValue(){
return this.value;
}
void setNext(Node next){
this.next = next;
}
Node getNext(){
return this.next;
}
}
public class NodeContainer {
Node tail;
Node head;
void setHead(int i) {
Node a = newNode(i);
head = a;
tail = a;
}
private Node newNode(int value) {
Node node = new Node();
node.setValue(i);
return node;
}
void addNode(int i) {
Node a = newNode(i);
Node tmp = this.head;
while(tmp.getNext() != null){
tmp = tmp.getNext();
}
tmp.setNext(a);
tail = a;
}
void addNode(int value, int index) {
//TODO : add check on head
Node a = newNode(value);
Node tmp = this.head;
int i = 0;
while(tmp.getNext()!=null && i < index) {
tmp = tmp.getNext();
i++;
}
//TODO : add check on tmp
Node next = tmp.getNext();
tmp.setNext(a);
a.setNext(next);
}
int count() {
//...
}
}

Sorting a generic LinkedList

I have to sort through a LinkedList, but i can't figure out why it only sorts it once and then stops. I am having a hard time understanding generic types and how to use them. Most of the examples i found were about sorting integer arrays, but i still couldn't translate those examples into my sort method. Anything that could help me understand how to sort this would be greatly appreciated.
public void sort() {
Node<T> current = head;
while(current != null){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
Here is my LinkedList class
public class LinkedList<T extends Comparable<T>> implements LinkedList161<T> {
protected Node<T> head;
protected int size;
public LinkedList() {
head = null;
size = 0;
}
public void add(T item, int index) {
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("out of bounds");
}
if(index == 0){
head = new Node<T>(item, head);
}
else{
Node<T> current = head;
for(int i = 0; i < index -1; i ++){
current = current.getNext();
}
current.setNext(new Node<T>(item, current.getNext()));
}
size++;
}
public void addFirst(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToFront(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToBack(T item) {
if(head == null){
head = new Node<T>(item);
size++;
}
else{
Node<T> temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
temp.setNext(new Node<T>(item));
size++;
}
}
public void remove(int index) {
if(index < 0 || index > size){
System.out.println("Index out of bounds");
}
if(index == 0){
head = head.getNext();
}else{
Node<T> current = head;
for(int i = 0; i < index;i++){
current = current.getNext();
}
current.setNext(current.getNext().getNext());
}
size--;
}
public T get(int index){
Node<T> p = head;
for(int i = 0; i < index;i++){
p = p.getNext();
}
return p.getItem();
}
public void clear() {
head = null;
size = 0;
}
public int size() {
return size;
}
#Override
public String toString() {
String result = "";
if (head == null)
return result;
for (Node<T> p = head; p != null; p = p.getNext()) {
result += p.getItem() + "\n";
}
return result.substring(0,result.length()-1); // remove last \n
}
#Override
public void sort() {
Node<T> current = head;
for(int i = 0; i < size;i++){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
}
Here is my Node class
public class Node<T> implements Node161<T>{
protected T item;
protected Node<T> next;
public Node(T item, Node<T> next) {
setItem(item);
setNext(next);
}
public Node(T item) {
setItem(item);
}
public T getItem() {
return item;
}
public void setItem(T i) {
item = i;
}
public void setNext(Node<T> n) {
next = n;
}
public Node<T> getNext() {
return next;
}
#Override
public String toString() {
return item.toString();
}
}
Your implementation of sort does just one step of sorting: it orders adjacent items and after this step things get better but the whole collection will not be sorted. You should repeat this step until your collection gets sorted.
Note that this algorithm is not efficient. You should look at some more sophisticated approach like merge sort
Wiki merge sort article now includes a simple but fast bottom up merge sort for linked lists that uses a small array (usually 26 to 32) of pointers to the first nodes of a list, where array[i] is either null or points to a list of size 2 to the power i. Unlike some other approaches, there's no scanning of lists, instead, the array is used along with a common merge function that merges two already sorted lists. Link to article:
http://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists

Copy a single Linked list with parameter (Node <E> node)

The problem I am facing is figuring out how to write a method
public SingleLinkedList copy(Node <E> node) {
}
To return a copy of the list. I have tried:
public SingleLinkedList copy(Node <E> node) {
SingleLinkedList<E> temp = new SingleLinkedList<E>();
Node<E> ref = head;
for(Node<E> n = ref ;ref!= null; n = n.next){
temp.add(n, ref.data);
ref = ref.next;
}
return temp;
}
I created a new list called temp, changed head to ref, iterate through the list and add it to the new list and return the new list, but there's an error with temp.add(n, ref.data).
What am I possibly doing wrong?
class SingleLinkedList<E> {
private static class Node<E> {
private E data;//removed final * private final E data
private Node<E> next;
private Node(E item) {
data = item;
}
}
private Node<E> head;
private int size;
/* Insert item at index, returns true if add is successful. */
public boolean add(int index, E item) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("" + index);
}
if (index == 0) { // adding to the front
Node<E> t = head;
head = new Node<>(item);
head.next = t;
} else { // adding anywhere other than front
Node<E> left = getNode(index - 1);
Node<E> node = new Node(item);
Node<E> right = left.next;
left.next = node;
node.next = right;
}
size++;
return true;
}
/* Add item at end of list, returns true if successful. */
public boolean add(E item) {
return add(size, item);
}
/* Return item at index */
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("" + index);
}
return getNode(index).data;
}
/* Return the number of items */
public int size() {
return size;
}
/* Returns a string representation of the list */
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (Node<E> n = head; n != null; n = n.next) {
sb.append(n.data);
sb.append(" ");
}
sb.append("]");
return sb.toString();
}
/* Return the node at location index */
private Node<E> getNode(int index) {
Node<E> n = head;
for (int i = 0; i < index; i++)
n = n.next;
return n;
}
The problem is you need to pass the position as an int. I also removed the Node n because you do not need it anyways.
I think this should work.
public SingleLinkedList copy() {
SingleLinkedList<E> temp = new SingleLinkedList<E>();
int i = 0;
for(Node<E> ref = head ;ref!= null; ref = ref.next){
temp.add(i++, ref.data);
}
return temp;
}
EDIT: I forgot to drop the parameter you do not need it at all.

Having some trouble using a Linked List and passing elements to the Node

In this specific instance, it takes into account two occasions. One where I'm trying to place a node in the beginning of the Linked List and one where I'm trying to place it in the middle or at the end. Here is my Node Class. If you look at my INSERT method, the part that is not working is:
Node newNode = new Node();
newNode.setExponent(element);
class Node {
private int coefficient;
private int exponent;
private Node link;
// Constructor: Node()
Node(int c, int e) {
// Sets coefficient to c, exponent to e, and link to null
coefficient = c;
exponent = e;
link = null;
}
// Inspectors: getCoefficient(), getExponent(), getLink()
public int getCoefficient() {
// Returns coefficient
return coefficient;
}
public int getExponent() {
// Returns exponent
return exponent;
}
public Node getLink() {
// Returns link
return link;
}
// Modifiers: setCoefficient(), setExponent(), setLink()
public void setCoefficient(int c) {
// Sets coefficient to c
coefficient = c;
}
public void setExponent(int e) {
// Sets exponent to e
exponent = e;
}
public void setLink(Node n) {
// Sets link to n
link = n;
}
}// Ends Node Class
Here is where I'm trying to insert to my Linked List along with some other methods in the class that should help give you an idea of how my code looks.
class List {
private Node head; // Points to first element of the list
private int count; // number of elements in the list
// Constructor:
List() {
// Sets head to null and count to zero
head = null;
count = 0;
}
// Inspectors:
// Returns the number of elements in the list
public int size() {
return count;
}
// Modifiers:
// Inserts element at index in the list. Returns true if successful
public boolean insert(int index, Node element) {
if (index < 0 || index > count)return false;
if (index == 0) {
Node newNode = new Node();
newNode.setExponent(element);
count++;
newNode.setLink(head);
head = newNode;
return true;
}
Node walker = head;
for (int i = 1; i < (index - 1); i++)
walker = walker.getLink();
Node newNode = new Node();
newNode.setExponent(element);
newNode.setLink(walker.getLink());
walker.setLink(newNode);
count++;
return true;
}
Try this:
Assumption: You are trying to insert a Node element into the index of LinkedList
Your insert method with modification.
public boolean insert(int index, Node element) {
//if (index < 0 || index > count)
if (index < 0 || index > count + 1) return false;
if(head == null) {
head = element;
return true;
}
if (index == 0) {
//Node newNode = new Node();
//newNode.setExponent(element);
count++;
element.setLink(head);
//newNode.setLink(head);
head = element;
//head = newNode;
return true;
}
Node walker = head;
//for (int i = 0; i < (index - 1); i++)
for (int i = 1; i < index; i++) {
walker = walker.getLink();
}
//Node newNode = new Node();
//newNode.setExponent(element);
element.setLink(walker.getLink());
//newNode.setLink(walker.getLink());
//walker.setLink(newNode);
walker.setLink(element);
count++;
return true;
}
Sample Test Case:
print method:
void print() {
Node travel = head;
while(travel!= null) {
System.out.println(travel.getExponent() + " " + travel.getCoefficient());
travel = travel.getLink();
}
}
Main method:
public static void main(String args[]) {
Node n1 = new Node(1,2);
List l = new List();
l.insert(0,n1);
Node n2 = new Node(3,2);
l.insert(1,n2);
Node n3 = new Node(4,5);
l.insert(0,n3);
l.print();
}

Inserting element in a doubly linked list

I'm trying to implement an insertAfterNth method that inserts an element after the nth(starting from 1, not 0) element on a doubly linked list. And, I'm stuck in setting the previous node to the node that I'm trying to insert. I need some help on figuring out the problem. Thanks.
public class DListNode {
public DListNode next;
public DListNode prev;
public int item;
...
}
public void insertAfterNth(int n, int item) {
if (n > length() || n < 1) {
System.out.println("error: out of bounds");
return;
}
else if (n == length()) {
insertEnd(item);
}
DListNode walker = head;
int i = 1;
while (i != n) {
i++;
walker = walker.next;
}
DListNode node = new DListNode(item);
node.next = walker.next;
walker.next.prev = node; /* not sure if this line of code is right, regardless this method is giving me errors(I'm most certain that this line is causing the problem)*/
walker.next = node;
node.prev = walker;
size++;
}
try using
(walker.next).prev
I might be wrong.
The code is mostly correct. You must add a method for inserting at the start of the list, but from your description/method name, it seems that you insert after a node so there may be no point in adding insertion at the start. You must check for the case when the head node is null. Another sugestion is to return a boolean value if the operation was successful. Another good return can be the newly inserted node or null if the operation failed. You may also throw an exception if you don't wish to return a value.
public class DoubleLinkedList {
private DListNode head;
private DListNode tail;
private int size;
private class DListNode {
private DListNode next;
private DListNode prev;
private int item;
private DListNode(final int item) {
this.item = item;
}
}
public void insertAfterNth(final int n, final int item) {
if (size == 0) {
System.out.println("error: list is empty");
} else if ((n > size) || (n < 1)) {
System.out.println("error: out of bounds");
return;
} else if (n == size) {
insertEnd(item);
}
DListNode walker = head;
int i = 1;
while (i < n) {
i++;
walker = walker.next;
}
DListNode node = new DListNode(item);
node.next = walker.next;
walker.next.prev = node;
walker.next = node;
node.prev = walker;
size++;
}
private void insertEnd(int item) {
size++;
final DListNode newItem = new DListNode(item);
if (head == null) {
head = newItem;
tail = newItem;
} else {
tail.next = newItem;
newItem.prev = tail;
tail = newItem;
}
}
public void add(final int item) {
insertEnd(item);
}
//the rest of operations you wish to implement
}

Categories