I've traced through my code to reverse a linked-list using recursion, and I cannot find anything wrong with it, but I know it does not work. Can anyone please explain why?
Node reverseLL (Node head) {
if(curr.next == null) {
head = curr;
return head;
}
Node curr = head.next;
prev = head;
head.next = prev;
head = next;
reverseLL(head.next);
}
Below is a working version of your code, added with some helping structures:
class LList {
Node head;
void reverse() {
head = rev(head, head.next);
}
private Node rev(Node node, Node next) {
if(next == null) return node; //return the node as head, if it hasn't got a next pointer.
if(node == this.head) node.next = null; //set the pointer of current head to null.
Node temp = next.next;
next.next = node; //reverse the pointer of node and next.
return rev(next, temp); //reverse pointer of next node and its next.
}
}
class Node {
int val;
Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
You need to call reverseLL(head.next) before the switching, to traverse down the list and start from the last node upwards. This requires some more changes though.
There are two possible implementation.
First one with a pointer to the head (a class attribute) within your class
class Solution:
head: Optional[ListNode]
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
node = head
if node == None:
return node
if node.next == None:
self.head = node
return
self.reverseList(node.next)
q = node.next
q.next = node
node.next = None
return self.head
Second solution, does not rely on a class attribute to conserve the head once you find it. It returns the pointer to the head through the recursive calls stack
def reverseList(head):
# Empty list is always None
if not head:
return None
# List of length 1 is already reversed
if not head.next:
return head
next = head.next
head.next = None
rest = reverseList(next)
next.next = head
return rest
Related
Here tail is a pointer to the last element of linked list.
This code only works when there are odd numbers of nodes in a linked list and shows wrong output for even number of nodes. Please help what is the problem in the code and reason why it is happening?
public static class Node
{
int data;
Node next;
}
public static class LinkedList
{
Node head;
Node tail;
int size;
// many other member functions
private void reversePRHelper(Node node , Node prev)
{
if(node == null)
{
return;
}
Node Next = node.next;
node.next = prev;
prev = node;
reversePRHelper(Next , prev);
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
}
public void reversePR()
{
reversePRHelper(head,null);
}
}
The bug in your code is that these three lines:
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
should only be executed once, at the end, and not for each recursive call. So if you move those three statements out of your reversePrHelper method and into your reversePR method, your code will work.
private void reversePRHelper(Node node , Node prev)
{
if(node != null)
{
return;
}
Node Next = node.next;
node.next = prev;
prev = node;
reversePRHelper(Next , prev);
}
public void reversePR()
{
reversePRHelper(head,null);
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
}
For me it is unclear however why you keep the tail as an attribute, since you can't navigate anywhere from the tail, as it has no next value. It would be different if your nodes would keep a reference to the previous element as well, but then it would be a double linked list.
(In the insert method): In the else statement, I don't understand how "front.next" is getting updated with the line: "prev.next = newNode". Theoretically, I understand it, but practically, although "prev" gets its value from "curr", which got its value from "front" itself, there is no way that front is getting updated because "prev". How are they talking to each other?
(Insert method)I have tried debugging and when it reaches the else statement that executes => prev.next = newNode; front.next gets updated as well which I just don't understand since front is nowhere being initialised again. Front is an object of itself.
public class SinglyLinkedList<T>
{
// inner class being created:
protected class Node<T extends Comparable<T>>
{
T val;
Node<T> next;
Node(T val)
{
this.val = val;
this.next = null;
}
Node(T val, Node n)
{
this.val = val;
this.next = n;
}
}
private Node front, tail;
public SinglyLinkedList()
{
this.front = this.tail = null;
}
// print method:
public void print()
{
// print the contents of the list
Node curr = front;
while (curr != null)
{
System.out.println(curr.val + " ");
curr = curr.next;
}
}
// insert method:
public void insert(T val)
{
Node newNode = new Node((Comparable) val);
// make a new node
if (front == null)
{
// empty list
front = tail = newNode;
}
else
{
// list is not empty
Node curr = front, prev = null;
// look for insert point.
while (curr != null && curr.val.compareTo(val) < 0)
{
prev = curr;
curr = curr.next;
}
// insert node before curr
newNode.next = curr;
if (curr == front)
{
// update front
front = newNode;
}
else
{
// update node before
prev.next = newNode;
}
if (tail.next != null)
{
// move tail to last node
tail = tail.next;
}
}
}
}
I expected curr to keep continuing to fill in the chain of nodes using curr.next and using "prev" as a temporary node used in the process of adding a node in between two nodes.
I also didn't expect print method to work since it begins with front node. Theoretically, it does make sense to start with front node, but looking at my code how "front" is not equalling to any value, but rather "curr" equalling "front", makes me feel that "front" shouldn't be having the access to the rest chain of nodes.
I expected "front.next" to be null, but it isn't.
Well, according to your code, the front works as the first node of the linked list, it actually equals to a certain value (a real node) because your code set it to be so a
if (front == null)
{
// empty list
front = tail = newNode;
}
and
if (curr == front)
{
// update front
front = newNode;
}
See! You indeed pointed it to a certain node with a given value.
For the update question. I think possibly you are always inserting a new node right next to the front node. Under that circumstance, the prev points to the same node as the front do. So if you update prev, you are updating front, too!
I learned most of the linked data structures using C++ where there is pass by reference available to you and recursion is pretty straightforward. I recently switched to Java and I always get confused with the recursive versions of these structures.
I wanna take the node out of the list. But I want to return the node. When I return the deleted node from the else if branch, it expectedly messes up the list. But I can't see a way around it.
public node deleteval (int val){
node prev = head;
head = deleteval(head,prev,val);
return head;
}
private node deleteval(node head,node prev, int val){
if(head == null){
return null;
}
else if (head.value == val){
prev.next = head.next;
node deleted = head;
head = prev;
return head.next;
}
prev = head;
head.next = deleteval(head.next,prev,val);
return head;
}
This is not a homework, just trying to understand. Thanks for any input.
To delete a node you only need to do prev.next = head.next and handle the edge case for root node. There is no need for a stack or any other supporting data structure, you simply recurse deeper into the list until you find the value or reach the end.
private Node root;
public Node deleteVal(int val) {
return deleteRec(root, null, val);
}
private Node deleteRec(Node head, Node prev, int val) {
if (head == null) {
return null;
}
if (head.value == val) {
if (prev != null) {
prev.next = head.next; // deleting non-root node
} else {
root = null; // deleting root node
}
return head;
}
return deleteRec(head.next, head, val);
}
I am having some trouble in deleting a node fro a circular linked list specifically deleting the head node.I tried to debug the code and problem that i found out was that the head node is not getting updated after deletion.that means if my list is 1->2->3->1(the 1 at the end here is actually the repetition of head node 1 to show circular link list ) and after trying to delete '1' the list becomes 1->2->3->2...So basically the the head node is not getting updated and hence when I try to print this linked list it enters infinite loop as the head node is encountered only once and the stopping condition is nover met again. below is the code which I have written for deletion
public class cirlinklist {
private int data;
private cirlinklist next;
private cirlinklist head;
public cirlinklist()
{
data = 0;
next = this;
}
public cirlinklist(int val)
{
data = val;
next = this;
}
public void cirlist(int val)
{
cirlinklist node = new cirlinklist(val);
if(this.next == this) //only one node present
{
node.next = this;
this.next = node;
}
else
{
cirlinklist temp = this.next;
//cirlinklist head = this;
/*while(node != head)
node = node.next;*/
node.next = temp.next; //adding after the last added node.For adding before last added node change to temp here and temp.next in next line
this.next.next = node;
}
}
public void printlist()
{
//cirlinklist head = this; //start node
cirlinklist node = this; //node for traversing and printing
System.out.println("Circular Link list data is:");
do
{
System.out.println(node.data);
node = node.next;
}
while(node != head);
System.out.println(node.data);
}
public void check()
{
}
public cirlinklist delete(int val)
{
head = this;
cirlinklist node = head;
cirlinklist node2 = node;
if(head.data == val) //if the node to be deleted is head node
{
//this = this.next;
while(node.next != head) //iterate till the last node i.e. the node which is pointing to head
{
node = node.next;
}
node.next = node.next.next; // update current node pointer to next node of head
//node = node.next;
head = head.next; //update head node
/*this.next = head.next.next;
this.data = head.next.data;*/
return this;
}
else // if node to be deleted is other than head node
{
while(node.data != val) // find the node
{
node = node.next;
node2.next = node;
}
node2.next = node.next; //updating next field of previous node to next of current node.current node deleted
node = null;
return this;
}
}
public static void main(String [] args)
{
cirlinklist obj = new cirlinklist(1);
cirlinklist obj2 = new cirlinklist();
//obj.cirlist(1);
obj.cirlist(2);
obj.cirlist(3);
obj.printlist();
obj2 = obj.delete(1);
System.out.println("Circular list after deletion is");
obj2.printlist();
}
}
Please tell me where I am going wrong
if(head.data == val) //if the node to be deleted is head node
{
//this = this.next;
while(node.next != head) //iterate till the last node i.e. the node which is pointing to head
{
node = node.next;
}
node.next = node.next.next; // update current node pointer to next node of head
//node = node.next;
head = head.next; //update head node
}
In this code, where is the head pointing to after
node.next = node.next.next ?
may be the problem lies there.
Since your code has changed quite a bit since this answer was posted, I am starting fresh. I can solve your problem as it exists currently, but you do have some issues with your list design that I will mention and suggest you redesign what you have.
First, your print function is breaking because you don't have anything that sets head, which you are using to determine when to keep printing.
Modify your constructors to:
public cirlinklist()
{
data = 0;
next = this;
head = this;
}
public cirlinklist(int val)
{
data = val;
next = this;
head = this;
}
Second, your delete function needs to return head since that's what you're modifying in that function.
I've posted the cleaner function here:
public cirlinklist delete(int val)
{
cirlinklist node = head;
if(head.data == val) //if the node to be deleted is head node
{
//this = this.next;
while(node.next != head) //iterate till the last node i.e. the node which is pointing to head
{
node = node.next;
}
node.next = node.next.next; // update current node pointer to next node of head
//node = node.next;
head = head.next; //update head node
/*this.next = head.next.next;
this.data = head.next.data;*/
return this;
}
else // if node to be deleted is other than head node
{
cirlinklist prev = node; // track previous node from current (node)
while(node.data != val) // find the node
{
prev = node;
node = node.next;
}
prev.next = node.next; //updating next field of previous node to next of current node.current node deleted
return head;
}
}
This should get you what you want.
However, there is a problem that you're not yet seeing, in that if you try to return head and then hope it's a copy of the list, it's not. You're actually modifying the head list and then distributing it to some other method when it returns, meaning that cirlist obj2 = obj.delete(1); is not going to give you a new copy of the deleted list, leaving obj untouched. You can see this if you add another delete operation after this one and print.
That being said, I modified the function to react properly when deleting a node in the middle.
One other thing you might also want to test for, is removing the tail node, as you might experience problems with that case too.
The last thing I would suggest is you redefine your data structures. You're using the identifier node in this case to represent a list node, when in fact, as you've got them defined, are actually lists themselves. A linked-list as is typically defined, is a bunch of nodes linked together, the entire collection being the list.
If you create a data structure to represent the node, that is, it's an object that has a data element, and a pointer to the next node, your list can be in a different class entirely and you can operate on the nodes while preserving only a single copy of the list, that you can control and copy with greater ease.
Something like this:
public class ListNode {
public int data;
public ListNode next = null;
public ListNode() {
data = 0;
}
public ListNode(int data) {
this.data = data;
}
public ListNode(ListNode node) {
if ( node != null) {
this.data = node.data;
this.next = node.next;
}
}
}
Then you can have another class that actually provides the operations
public class CircularLinkedList {
public ListNode head;
public CircularLinkedList(...) {}
public void addToList(int data) {}
public void deleteFromList(int data) {}
... // and so-on
}
The head in this case, is your list, and any time you make changes or need to manipulate it, you can define functions that will do so in terms of head and then act appropriately.
Good luck to you
My problem is: Given a function to reverse a linked list.
My attempt at it in C was:
ListNode *reverse(ListNode *head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode *temp = head->next;
ListNode *retP = reverse(temp);
temp->next = head;
head->next = NULL;
return retP;
}
But I do not think this is right. I want to be able to do it in Java and I am stumped on this. Any help would be appreciated. Please help me get started
If you want to reverse a List in Java, use
Collections.reverse(List list)
If you want to know how it is implemented or want to do it by hand, have a look at the JDK sources of java.util.Collections.
Iteratively
public reverseListIteratively (Node head) {
if (head == NULL || head.next == NULL)
return; //empty or just one node in list
Node Second = head.next;
//store third node before we change
Node Third = Second.next;
//Second's next pointer
Second.next = head; //second now points to head
head.next = NULL; //change head pointer to NULL
//only two nodes, which we already reversed
if (Third == NULL)
return;
Node CurrentNode = Third;
Node PreviousNode = Second;
while (CurrentNode != NULL)
{
Node NextNode = CurrentNode.next;
CurrentNode.next = PreviousNode;
/* repeat the process, but have to reset
the PreviousNode and CurrentNode
*/
PreviousNode = CurrentNode;
CurrentNode = NextNode;
}
head = PreviousNode; //reset the head node
}
Recursively
public void recursiveReverse(Node currentNode )
{
//check for empty list
if(currentNode == NULL)
return;
/* if we are at the TAIL node:
recursive base case:
*/
if(currentNode.next == NULL)
{
//set HEAD to current TAIL since we are reversing list
head = currentNode;
return; //since this is the base case
}
recursiveReverse(currentNode.next);
currentNode.next.next = currentNode;
currentNode.next = null; //set "old" next pointer to NULL
}
Source, with explanation (after using google for 3 seconds) http://www.programmerinterview.com/index.php/data-structures/reverse-a-linked-list/
public Node reverse(Node node){
Node p=null, c=node, n=node;
while(c!=null){
n=c.next;
c.next=p;
p=c;
c=n;
}
return p;
}