This question already has answers here:
Reversing a linked list in Java, recursively
(33 answers)
Closed 6 years ago.
I'm trying to reverse a LinkedList using recursive calls, please let me know where I'm going wrong, I'm not able to catch reversed LL head.
LLNode is a linkedlist node and ReverseLLRecursively.reverse is the function I wrote for reversing.
Here is my code:
public class LLNode {
private int data;
private LLNode next;
public LLNode(int data, LLNode next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
#Override
public String toString() {
return data + "->[" + (next!=null?next.data:"") + "]";
}
}
public class ReverseLLRecursively {
public static LLNode newHead = new LLNode(-1, null);
public static LLNode reverse(LLNode head, LLNode newHead) {
if(head==null || head.getNext()==null) {
newHead = head;
return head;
}
LLNode node = reverse(head.getNext(), newHead);
node.setNext(head);
head.setNext(null);
return node.getNext();
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
reverse(ll , newHead);
System.out.println(newHead);
}
}
You are overcomplicating your problem and work with a local variable which has the same name as a static member. This should be simpler:
public static LLNode reverse(LLNode previous) {
if(previous==null) {
return null;
}
LLNode toReturn = (previous->getNext() == null) ? previous : reverse(previous.getNext());
previous.getNext().setNext(previous);
return toReturn;
}
Note, that toReturn will be the new head.
Making the reverse a method of LLNode, makes stuff somewhat easier.
You want to return the last value (and only the last) in your linked list. If you have it, return, otherwise go deeper until you have it. After you have the end, store it, setNext as you don't need the value of next anymore, return the end.
public LLNode reverse(LLNode previous) {
if(getNext()==null) {
setNext(previous);
return this;
}
LLNode returnValue = getNext().reverse(this);
setNext(previous);
return returnValue;
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
ll = ll.reverse(null);
System.out.println(ll);
}
Otherwise the static variant if you need it for whatever reason.
public static LLNode reverse(LLNode current) {
if(current.getNext()==null) {
return current;
}
LLNode returnValue = reverse(current.getNext());
current.getNext().setNext(current);
current.setNext(null);
return returnValue;
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
ll = reverse(ll);
System.out.println(ll);
}
Related
i have a problem that the method in LinkedList class don't print anything.. and i'm trying hard to know what's the problem i hope someone help
the main class
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.printAllNodes();
}
}
LinkedList class
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
why it dosn't print i tried so hard
This is because you never add any nodes to your LinkedList.
Code could be as follows. Beware, nodes will be added at the beginning of list.
Main class:
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.add(a).add(b).add(c);
List1.printAllNodes();
}
}
LinkedList class:
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public LinkedList add(LLnode node){
LLnode oldHead = this.head();
this.head = node;
node.setNext(oldHead);
return this;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
}
import java.util.*;
public class Intersection
{
private Node head;
private Node head1;
private Node head2;
private Node current1;
private Node current2;
private int l1;
private int l2;
public Intersection()
{
head= new Node(null);
head1= new Node(null);
head2= new Node(null);
Node current1= head1;
Node current2= head2;
l1=0;l2=0;
}
public static void main(String[] args)
{
Intersection obj= new Intersection();
LinkedList<Object> list1 = new LinkedList<Object>();
LinkedList<Object> list2 = new LinkedList<Object>();
list1.add(3);
list1.add(6);
list1.add(9);
list1.add(15);
list1.add(30);
list2.add(10);
list2.add(15);
list2.add(30);
Object ans= obj.method(obj.head1, obj.head2);
System.out.println(ans);
}
public Object method(Node current1, Node current2)
{
int diff;
if(current1== null || current2== null)
{
return null;
}
while(current1.getNext() != null)
{
l1++;
current1=current1.getNext();
}
while(current2.getNext() != null)
{
l2++;
current2=current2.getNext();
}
if(l1>l2)
{
diff=l1-l2;
int j=0;
while(j<diff)
{
current1=current1.getNext();
j++;
}
}
else
{
diff=l2-l1;
int j=0;
while(j<diff)
{
current2=current2.getNext();
j++;
}
}
while(current1!= null || current2!= null)
{
if(current1.getData()==current2.getData())
return current1.getData();
current1=current1.getNext();
current2=current2.getNext();
}
return null;
}
private class Node
{
Node next;
Object data;
public Node(Object _data)
{
next= null;
data= _data;
}
public Node(Node _next, Object _data)
{
next= _next;
data= _data;
}
public Object getData()
{
return data;
}
public void setData(Object _data)
{
data = _data;
}
public Node getNext()
{
return next;
}
public void setNext(Node _next)
{
next = _next;
}
}
}
Above is my code to find out the intersection of the linked list in which there is no error.
I am having problem in how to create 2 different linked lists and then print the intersection of the linked list.
Please give some suggestions.
This is how to create LinkedList, where Object is the Type you would hold in your list:
LinkedList<Object> list1 = new LinkedList<Object>();
to create second LinkedList:
LinkedList<Object> list2 = new LinkedList<Object>();
After that you have two lists: list1 and list2,is this what you need?
Intersection:
list1.retainAll(list2);
and list1 will have the intersection :)
I can't figure why the addition to the tail of this LinkedList class is not working and is simply ignored in the output.
Here's a simple Node class:
public class IntNode {
private int val;
private IntNode next;
public IntNode() {
this.val = 0;
IntNode next = null;
}
public IntNode(int val) {
this.val = val;
this.next = null;
}
public IntNode next() {
return this.next;
}
public int getVal() {
return this.val;
}
public void setNextNode(int val) {
this.next = new IntNode(val);
}
public void setNextNode(IntNode a)
{
this.next = new IntNode(a.getVal());
}
public void setVal(int val) {
this.val = val;
}
public String toString() {
StringBuffer buff = new StringBuffer();
return toString(this, buff);
}
private String toString(IntNode node, StringBuffer buff) {
if (node == null) {
return buff.toString();
}
buff.append(node.val);
if (node.next != null) {
buff.append(", ");
} else {
buff.append(".");
}
return toString(node.next(), buff);
}
}
And here's the linked list for it:
public class LinkedList {
private IntNode header;
private IntNode trailer;
private int listSize;
public LinkedList()
{
this.header = null;
this.trailer = null;
this.listSize = 0;
}
public LinkedList(IntNode a, IntNode b)
{
this.header = a;
this.trailer = b;
this.header.setNextNode(this.trailer);
this.listSize = 2;
}
public void addNode(IntNode a)
{
this.trailer.setNextNode(a.getVal());
this.trailer = this.trailer.next();
this.listSize++;
}
public String toString()
{
return this.header.toString();
}
public static void main(String args[])
{
LinkedList lst = new LinkedList(new IntNode(1), new IntNode(2));
lst.addNode(new IntNode(3));
lst.addNode(new IntNode(4));
System.out.println(lst.toString());
}
}
The output of the main method is: 1, 2.
Why is the addition method not working?
In your constructor with two IntNodes, your header is not pointing to your trailer. Instead it points to a new IntNode(trailer.val). You should change
public void setNextNode(IntNode a)
{
this.next = a;
}
Your problem is that the LinkedList constructor sets header to a and trailer to b, but then calls header.setNextNode(this.trailer);
IntNode's method setNextNode() method discards the node that it is passed and instead creates a node with the same value as the one that it had passed in.
This means that at the end of your LinkedList constructor you have the header assigned to a which has a next node value of something other than b that has the same value as b, while trailer is set to b.
You should change your setNextNode() method to not discard the node it's handed in, as follows:
public void setNextNode(IntNode a) {
this.next = a;
}
In the constructor of the LinkedList class you have the code this.header.setNextNode(this.trailer);. This will not set the next node of the head to the trailer, but set the next node of the head to another node with the value of the trailer. When the trailer's next node is set, the head is not affected.
My first assignment in my programming class is about writing code for a Doubly Linked List, which includes writing an add, remove, size, iterator first, iterator last, and iterator find functions. I have spent 3 hours and gotten no where in understanding this. I understand what happens if I can see it in a picture. But my problem is translating it to code. This is what I have so far:
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data, node next, node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null, null, null);
footer = new node(null, header, null);
header.next = footer;
}
public void add(G data) {
header.next = new node(data, footer.prev, footer);
}
public int size() {
node current = header.next;
int quanity = 0;
if (current == null) {
return 0;
}
while (current != null) {
current = current.next;
quanity++;
}
return quanity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
As you can see, I've been using the main() to test everything. From what I've been told by my teacher, my constructor and node class look fine. However I know either my add and size are not right because when I test this, when there is no nodes in the list, it displays nothing, but it should display 0 right? I mean, assuming my size code is right, which I'm not sure of.
And whenever I add a node, no matter how many I add, it always displays 1. So either both add and size are broken, or both are. I have not written the other functions as it makes no sense until I figure these ones out. Please someone help me understand this! Thank you.
Declare a size field in DoublyLinkedList to store the current size of the list. When add succeed, make size++. When remove succeed, make size--. And size() method just simply return the value of size.
The sample code is here:
private int size = 0;
public void add(G data) {
header.next = new node(data, footer.prev, footer);
size++;
}
public int size() {
return size;
}
Noticed couple of things:
First, footer is not constructed correctly. It should be:
public DoublyLinkedList() {
..
footer = new node(null, null, header);
// your code is incorrectly creating a circular list
..
}
Secondly add() method doesn't look correct. It should be something like :
public void add(G data) {
Node newNode = new Node(data, header, null);
header.prev = newNode
header = newNode;
}
// for adding at the front (LIFO)
OR
public void add(G data) {
Node newNode = new Node(data, null, footer);
footer.next = newNode
footer = newNode;
}
//for adding at the tail (FIFO)
Check out the wikipedia entry for doubly linked lists. It has some good pseudo code.
Using your own code I'm going to make a few suggestions
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null);
footer = new node(null);
header.next = footer;//link the header to the footer
footer.prev = header;//link the footer to the header
}
public void add(G data) { //assuming you are adding the node to the head of the list
node newNode = new node(data); //creating new node to add with the data
newNode.next = header.next; // setting new node to head of the list or the footer
newNode.prev = header; //setting the new node's previous node to the header
header.next = newNode; //setting the newNode as the next node.
}
public int size() {
node current = header.next;
int quantity = 0;
if (current.data == null/*Empty list*/) { //you needed to specify what you were trying to test
return 0;
}
while (current.data != null/*traversing the list*/) {
current = current.next;
quantity++;
}
return quantity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
Here you go:
public class DoublyLinkedList {
private class Node {
String value;
Node next,prev;
public Node(String val, Node n, Node p) {
value = val;
next = n;
prev=p;
}
Node(String val) {
this(val, null, null);
}
}
private Node first;
private Node last;
public DoublyLinkedList() {
first = null;
last = null;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
int count=0;
Node p=first;
while(p!=null){
count++;
p=p.next;
}
return count;
}
public void add(String e) {
if(isEmpty()){
last=new Node(e);
first=last;
}
else{
last.next=new Node(e, null, last);
last=last.next;
}
}
public void add(int index, String e){
if(index<0||index>size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if(index==0){
Node p=first;
first=new Node(e,p,null);
if(p!=null)
p.prev=first;
if(last==null)
last=first;
return;
}
Node pred=first;
for(int k=1; k<=index-1;k++){
pred=pred.next;
}
Node succ=pred.next;
Node middle=new Node(e,succ,pred);
pred.next=middle;
if(succ==null)
last=middle;
else
succ.prev=middle;
}
public String toString(){
StringBuilder strBuilder=new StringBuilder();
Node p=first;
while(p!=null){
strBuilder.append(p.value+"\n");
p=p.next;
}
return strBuilder.toString();
}
public String remove(int index){
if(index<0||index>=size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
Node target=first;
for(int k=1; k<=index;k++){
target=target.next;
}
String element=target.value;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return element;
}
public boolean remove(String element){
if(isEmpty())
return false;
Node target=first;
while(target!=null&&!element.equals(target.value))
target=target.next;
if(target==null)
return false;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return true;
}
public static void main(String[] args){
DoublyLinkedList list1=new DoublyLinkedList();
String[] array={"a","c","e","f"};
for(int i=0; i<array.length; i++){
list1.add(array[i]);
}
list1.add(1,"b");
list1.add(3,"d");
System.out.println(list1);
}
}
I thought I had this program working but unfortunately I've overlooked something. How do you delete the first Node and convert the second node into the front of the Linked List. I've tries a multitude of approaches but end up with the same result.(LinkedList remaining unchanged) Any guidance would be much appreciated.
Node Class
public class Node {
private String data;
private Node next;
Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
Main
public static void main(String[] args) {
Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
list = insertSecond(list,"New Node");
list = addLast(list,"LAST NODE");
printList(list);
System.out.println();
deleteNode(list, "NODE 1");
printList(list);
}
public static Node deleteNode(Node list,String str)
{
Node temp = list;
Node prev = list;
while(temp != null)
{
if(temp.getData().equals(str))
{
if(temp.getData().equals(list.getData()))
{
list = list.getNext();
return deleteNode(list,str);
}
else
{
prev.setNext(prev.getNext().getNext());
}
}
prev = temp;
temp = temp.getNext();
}
return list;
Your deleteNode function should return the head of new list. This is required only in one edge case which you described - deleting head of that list.
list = deleteNode(list, str);
Also you don't need to recursively execute deleteNode method, iteration over node elements should be enough:
public static Node deleteNode(Node list, String str) {
// I'm assuming that you are deleting the first inscance of the string
Node temp = list;
Node prev = list;
while(temp != null) {
if(temp.getData().equals(str)) {
if(temp.getData().equals(list.getData())) {
return list.getNext();
}
else {
prev.setNext(temp.getNext());
return list;
}
}
prev = temp;
temp = temp.getNext();
}
return list;
}